将 foreach 与 ArrayList 一起使用 - 自动转换? [英] Using foreach with ArrayList - automatic casting?

查看:28
本文介绍了将 foreach 与 ArrayList 一起使用 - 自动转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

foreach(string s in x)
{
}

这是否意味着当 foreach 运行时,它会尝试将数组列表的元素强制转换为输入 foreach 表达式?

Does it mean that when foreach is run it tries to cast element of array list to type in foreach expression?

推荐答案

是的,如果元素无法转换为类型,您将收到 InvalidCastException.在您的情况下,您不能将盒装 int 转换为 string 导致抛出异常.

Yes, if an element is not convertible to the type, you'll get an InvalidCastException. In your case, you cannot cast boxed int to string causing an exception to be thrown.

本质上,它相当于:

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

这篇关于将 foreach 与 ArrayList 一起使用 - 自动转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆