简体   繁体   中英

foreach on System.Array

Given the following code:

static void Main() {
    string[] myArray = {"One", "Two", "Three"};

    PrintArray(myArray);
}

static void PrintArray(System.Array array1) {

    foreach (string s in array1) 
        Console.WriteLine(s);
}

I'm surprised that I could compile those lines without error, since in PrintArray the compiler cannot know what kind of array array1 is (in this case it's System.string[] ). If I change the foreach line as such: foreach (int s in array1) , the code will still compile, but will generate an runtime invalid casting exception.

Shouldn't the compile in this case assure only Object could be used in the foreach statement?

By specifying the type of the loop variable you are explicitly unboxing/casting each element in your array as that type.

In the case of a string, it is a cast from object to string.
If your array would be an int array you would be doing an unboxing operation instead of a cast.

The compiler knows that you are passing in a System.Array , which is an object -based collection. It cannot statically know what kind of objects the array contains so there's no way to assure that the code will run without errors in the general case. The cast to int has to be performed at runtime and might fail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM