110,535
社区成员
发帖
与我相关
我的任务
分享
ArrayList x=new ArrayList(); x.Add(10); x.Add("SS"); foreach(string s in x) { }
如这段代码,foreach语句也可以这样写:
foreach (Object stemp in x)
{
Console.WriteLine(stemp.ToString() + " ");
}
foreach语句相比for的好处在于同样实现遍历,但去掉了迭代器,不需要进行边界检查。要知道数组越界是常见问题。ArrayList x=new ArrayList();
x.Add(10);
x.Add("SS");
foreach(string s in x)
{
}
编译器展开成等价如下形式的代码:
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();
}
注意编译器会在***********处增加强制类型转换。
如果ArrayList中的元素不都是string,会报运行时错误。