Foreach can throw an InvalidCastException?

后端 未结 3 2070
我在风中等你
我在风中等你 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:02

    With C# 3 I'm using var - so I get the compiler warnings.

    0 讨论(0)
  • 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<T>, if it is implemented by the collection.

    0 讨论(0)
  • 2020-12-03 11:22

    Think back to before generics... foreach had to cast so that you could do sensible things like:

    foreach (string x in names)
    {
        // ...
    }
    

    instead of:

    foreach (object tmp in names)
    {
        string x = (string) tmp;
        // ...
    }
    

    The latter is just icky, IMO. Providing an implicit cast is unlike the rest of the language, but makes it much easier to use in the vast majority of cases.

    I suspect that if C# had had generics and extension methods to start with (so we could use OfType and Cast) that foreach wouldn't be specified in quite the same way.

    Note that there's even more oddness in foreach: the type doesn't have to implement IEnumerable at all. So long as it has a GetEnumerator method which returns something which in turn has MoveNext() and Current, the C# compiler is happy. This meant you could implement a "strongly typed iterator" (to avoid boxing) before generics.

    0 讨论(0)
提交回复
热议问题