Foreach can throw an InvalidCastException?

后端 未结 3 2071
我在风中等你
我在风中等你 2020-12-03 10:47

Imagine the following code:

class foreach_convert
{
    public static void method2()
    {
        List x = new List();         


        
3条回答
  •  死守一世寂寞
    2020-12-03 11:16

    foreach works on IEnumerable, which returns objects of type object. For every item, the object will be cast to the type you provided.

    Unless you use var in C# 3.0. Then the type will be taken from IEnumerable, if it is implemented by the collection.

提交回复
热议问题