簡體   English   中英

為什么Enumerable.Except可以在C#中的字符串數組上使用?

[英]Why can Enumerable.Except be used on a string array in C#?

這是我在Pete on Software博客找到的代碼示例:

var listThree = new string[] { "Pete", "On", "Software" };  
var listFour = new string[] { "Joel", "On", "Software" };  
stringExcept = listThree.Except(listFour);

代碼編譯並運行。 到現在為止還挺好。

但是,我不明白為什么會這樣。

那么,任何人都可以解釋為什么我可以在字符串數組上使用Enumerable.Except嗎?

也許,如果有人能解釋如何閱讀Enumerable.Except的簽名,我會很清楚,並給我一個代碼示例:

public static IEnumerable<TSource> Except<TSource>(
    this IEnumerable<TSource> first,
    IEnumerable<TSource> second
)

我知道的

我知道泛型和擴展方法的概念。 但顯然不足以理解上面的代碼示例。 我也已經使用了一些基本的Linq查詢。

Except是擴展方法,它擴展了實現IEnumerable<T>任何類型。 這包括實現IEnumerable<T>System.Array類型。

鏈接頁面上的注釋解釋了為什么文檔不顯示實現IEnumerable<T> System.Array

在.NET Framework 2.0版中,Array類實現System.Collections.Generic.IList<T>System.Collections.Generic.ICollection<T>System.Collections.Generic.IEnumerable<T>泛型接口。 這些實現在運行時提供給數組,因此文檔構建工具不可見。 因此,通用接口不會出現在Array類的聲明語法中,並且沒有可通過將數組轉換為通用接口類型(顯式接口實現)來訪問的接口成員的參考主題。 將數組轉換為其中一個接口時要注意的關鍵是添加,插入或刪除元素的成員會拋出NotSupportedException

它只是說如果在這種情況下你有一個給定類型TSourceIEnumerable string你可以用另一個相同類型的IEnumerable除外它並獲得相同類型的第三個IEnumerable 關鍵點是兩個IEnumerable輸入必須相同(顯然返回的類型相同)。

T(或者說T[] )的數組也是IEnumerable<T> 在您的問題中,T是System.String 並且Enumerable.ExceptIEnumerable<T>的擴展方法,因此它也適用於string[] stringExcept = listThree.Except(listFour); 等於

stringExcept = Enumerable.Except(listThree, listFour).

編譯器將TSource參數與string匹配,因為字符串數組實現IEnumerable<string>接口,因此匹配擴展方法的第一個參數。 所以答案是兩件事:

  • string[]實現IEnumerable<string>
  • 編譯器足夠智能以推斷泛型參數

Except方法返回第一個可枚舉中的元素,這些元素也不會出現在第二個可枚舉中。 所以在你指定的情況下,結果將是{"Pete", "Joel"}

在這種情況下,考慮字符串數組可能是一個紅色的鯡魚。 從對象平等的角度考慮可能更有利( http://msdn.microsoft.com/en-us/library/system.object.equals.aspx)

Microsoft文檔位於: http//msdn.microsoft.com/en-us/library/system.linq.enumerable.except.aspx

暫無
暫無

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

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