2011-01-22 39 views
10
ArrayList x=new ArrayList(); 
x.Add(10); 
x.Add("SS"); 

foreach(string s in x) 
{ 
} 

这是否意味着当foreach运行时它会尝试抛出数组列表的元素来输入foreach表达式?使用foreach与ArrayList - 自动铸造?

+3

运行代码,看看。 – BoltClock 2011-01-22 11:29:10

回答

10

是的,如果一个元素不能转换成这个类型,你会得到一个InvalidCastException。在你的情况下,你不能投出盒装intstring,导致抛出异常。当您运行循环,并投它时,编译器会尝试将它转换为指定的类型,这在你的情况下,将字符串

当然
foreach (object __o in list) { 
    string s = (string)__o; 
    // loop body 
} 
1

是:

从本质上讲,它是相当于。如果它不能这样做会引发InvalidCastException。

8

根据foreach语句C#specification,你的代码就相当于

ArrayList x=new ArrayList(); 
x.Add(10); 
x.Add("SS"); 

IEnumerator enumerator = (x).GetEnumerator(); 
try { 
    while (enumerator.MoveNext()) { 
     string element = (string)enumerator.Current; // here is casting occures 
     // loop body; 
    } 
} 
finally { 
    IDisposable disposable = enumerator as System.IDisposable; 
    if (disposable != null) disposable.Dispose(); 
}