obtain generic enumerator from an array

前端 未结 7 1245
感情败类
感情败类 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:25

    To Make it as clean as possible I like to let the compiler do all of the work. There are no casts (so its actually type-safe). No third party Libraries (System.Linq) are used (No runtime overhead).

        public static IEnumerable GetEnumerable(this T[] arr)
        {
            return arr;
        }
    

    // And to use the code:

        String[] arr = new String[0];
        arr.GetEnumerable().GetEnumerator()
    

    This takes advantage of some compiler magic that keeps everything clean.

    The other point to note is that my answer is the only answer that will do compile-time checking.

    For any of the other solutions if the type of "arr" changes, then calling code will compile, and fail at runtime, resulting in a runtime bug.

    My answer will cause the code to not compile and therefore I have less chance of shipping a bug in my code, as it would signal to me that I am using the wrong type.

提交回复
热议问题