obtain generic enumerator from an array

前端 未结 7 1240
感情败类
感情败类 2020-12-08 12:23

In C#, how does one obtain a generic enumerator from a given array?

In the code below, MyArray is an array of MyType objects. I\'d like to

7条回答
  •  死守一世寂寞
    2020-12-08 13:27

    You can decide for yourself whether casting is ugly enough to warrant an extraneous library call:

    int[] arr;
    IEnumerator Get1()
    {
        return ((IEnumerable)arr).GetEnumerator();  // <-- 1 non-local call
    
        // ldarg.0 
        // ldfld int32[] foo::arr
        // castclass System.Collections.Generic.IEnumerable`1
        // callvirt instance class System.Collections.Generic.IEnumerator`1 System.Collections.Generic.IEnumerable`1::GetEnumerator()
    }
    
    IEnumerator Get2()
    {
        return arr.AsEnumerable().GetEnumerator();   // <-- 2 non-local calls
    
        // ldarg.0 
        // ldfld int32[] foo::arr
        // call class System.Collections.Generic.IEnumerable`1 System.Linq.Enumerable::AsEnumerable(class System.Collections.Generic.IEnumerable`1)
        // callvirt instance class System.Collections.Generic.IEnumerator`1 System.Collections.Generic.IEnumerable`1::GetEnumerator()
    }
    

    And for completeness, one should also note that the following is not correct--and will crash at runtime--because T[] chooses the non-generic IEnumerable interface for its default (i.e. non-explicit) implementation of GetEnumerator().

    IEnumerator NoGet()                    // error - do not use
    {
        return (IEnumerator)arr.GetEnumerator();
    
        // ldarg.0 
        // ldfld int32[] foo::arr
        // callvirt instance class System.Collections.IEnumerator System.Array::GetEnumerator()
        // castclass System.Collections.Generic.IEnumerator`1
    }
    

    The mystery is, why doesn't SZGenericArrayEnumerator inherit from SZArrayEnumerator--an internal class which is currently marked 'sealed'--since this would allow the (covariant) generic enumerator to be returned by default?

提交回复
热议问题