c# - yield return返回什么样的类

标签 c#

所以我注意到这段代码有效:

class Program
{
    public static void Main()
    {
        Int32[ ]numbers = {1,2,3,4,5};

        using (var enumerator = Data().GetEnumerator())
        {

        }
    }

    public static IEnumerable<String> Data()
    {
        yield return "Something";
    }
}

特别是,我对 using block 很好奇,因为:

Int32[] numbers = { 1, 2, 3, 4, 5, 6 };

using (var enumerator = numbers.GetEnumerator())
{

}

因编译器错误而失败。显然,yield return 返回的类是 IDisposable 而常规数组枚举器不是。所以现在我很好奇:yield return 究竟创造了什么?

最佳答案

IEnumerator<T>工具 IDisposable ,如您在对象浏览器或 MSDN 中所见。

非泛型 IEnumerator没有。

基地Array类(class)工具IEnumerable但不是 IEnumerable<T> . (因为 Array 不是通用的)
具体数组类型确实实现了 IEnumerable<T> , 但他们实现 GetEnumerator()明确地(我不确定为什么)。
因此,GetEnumerator()在任何数组类型上可见返回 IEnumerator .

通用 IEnumerable<T>实现返回 System.SZArrayHelper.SZGenericArrayEnumerator<T> .

此类的源代码(在 Array.cs 中)具有以下注释,部分解释了这一点(请记住,对泛型数组的所有支持都可以追溯到 IEnumerable<T> 不违反的时代)

//--------------------------------------------------------------------------------------- 
// ! 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<T>, 
// IList<T.BaseType>, etc., etc. all the way up to IList<Object>. When the following call is 
// made:
// 
//   ((IList<T>) (new U[n])).SomeIListMethod()
//
// the interface stub dispatcher treats this as a special case, loads up SZArrayHelper,
// finds the corresponding generic method (matched simply by method name), instantiates 
// it for type <T> and executes it.
// 
// The "T" will reflect the interface used to invoke the method. The actual runtime "this" will be 
// array that is castable to "T[]" (i.e. for primitivs and valuetypes, it will be exactly
// "T[]" - for orefs, it may be a "U[]" where U derives from T.) 
//---------------------------------------------------------------------------------------

关于c# - yield return返回什么样的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15341882/

相关文章:

c# - 消息框的大小

c# - 有没有办法将 OwinRequest 转换为 HttpRequestBase?

c# - 如何将代码隐藏中的自定义对象绑定(bind)到 XAML 中的网格?

c# - C#/WPF 中的 NEON /发光效果

c# - 如果我输入搜索参数,如何让机器人框架机器人发回数据库的单元格?

c# - WPF TextBlock 绑定(bind)不起作用

c# - 跨线程操作无效 : Control 'textBox1' accessed from a thread other than the thread it was created on

c# - Azure 计费使用 API 返回 401 未经授权

c# - 如何在 ASP.NET Identity 中创建默认密码

C# 正则表达式忽略转义字符