什么样的阶级会产生回报
所以我注意到这段代码有效:
class Program { public static void Main() { Int32[ ]numbers = {1,2,3,4,5}; using (var enumerator = Data().GetEnumerator()) { } } public static IEnumerable Data() { yield return "Something"; } }
特别是,我对using
块感到好奇,因为:
Int32[] numbers = { 1, 2, 3, 4, 5, 6 }; using (var enumerator = numbers.GetEnumerator()) { }
因编译器错误而失败。 显然, yield return
返回的类是IDisposable
而常规数组枚举器则不是。 所以现在我很好奇: yield return
到底创造了什么?
IEnumerator
实现了IDisposable
,您可以在对象浏览器或MSDN中看到。
非通用的IEnumerator
没有。
基类Array
类实现IEnumerable
但不实现IEnumerable
。 (因为Array
不是通用的)
具体的数组类型确实实现了IEnumerable
,但是它们实现了GetEnumerator()
(我不知道为什么)。
因此,任何数组类型上可见的GetEnumerator()
返回IEnumerator
。
通用IEnumerable
实现返回System.SZArrayHelper.SZGenericArrayEnumerator
。
这个类的源代码(在Array.cs
)有以下注释,部分解释了这一点(记住,对generics数组的所有支持都可以追溯到IEnumerable
不相反的时候)
//--------------------------------------------------------------------------------------- // ! READ THIS BEFORE YOU WORK ON THIS CLASS. // // The methods on this class must be written VERY carefully to avoid introducing security holes. // That's because they are invoked with special "this"! The "this" object // for all of these methods are not SZArrayHelper objects. Rather, they are of type U[] // where U[] is castable to T[]. No actual SZArrayHelper object is ever instantiated. Thus, you will // see a lot of expressions that cast "this" "T[]". // // This class is needed to allow an SZ array of type T[] to expose IList, // IList, etc., etc. all the way up to IList