簡體   English   中英

什么樣的課程會產生回報

[英]What kind of class does yield return return

所以我注意到這段代碼有效:

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塊感到好奇,因為:

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

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

}

因編譯器錯誤而失敗。 顯然, yield return返回的類是IDisposable而常規數組枚舉器不是。 所以現在我很好奇: yield return到底創造了什么?

IEnumerator<T>實現了IDisposable ,您可以在對象瀏覽器或MSDN中看到。

非通用的IEnumerator沒有。

基類Array類實現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.) 
//---------------------------------------------------------------------------------------

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM