簡體   English   中英

為什么列表的枚舉器 <T> 是公開的?

[英]Why the Enumerator of List<T> is public?

列表中枚舉器上的公共訪問修飾符的原因是什么?

我希望私有修飾符而不是公共修飾符。

列出源代碼

它是公共的,因此可以聲明 GetEnumerator()方法返回它。

然后允許C#編譯器在foreach循環中使用它...避免任何堆分配, 因為List.Enumerator是一個結構 (一個可變的結構,讓我走“呃!”但這是另一個故事。)

所以當你有類似的東西:

List<string> list = new List<string> { "..." };
foreach (var item in list)
{
    Console.WriteLine(item);
}

然后編譯器可以將其轉換為:

List<string> list = new List<string> { "..." };
using (List<string>.Enumerator enumerator = list.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        string item = enumerator.Current;
        Console.WriteLine(item);
    }
}

請注意這里的enumerator類型 - 如果我們有:

IEnumerable<string> list = new List<string> { "..." };
foreach (var item in list)
{
    Console.WriteLine(item);
}

它會使用:

using (IEnumerator<string> enumerator = list.GetEnumerator())

...涉及堆分配,因為IEnumerator<string>是引用類型。 List<T>GetEnumerator()IEnumerable<T>實現返回一個裝箱的 List<string>.Enumerator

僅僅因為它在許多其他組件中被重用。

您可以討論這是否是使用結構而不是底層接口的正當理由,但這是我猜的最重要的原因。

暫無
暫無

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

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