例
这是我在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类型。
链接页面上的注释说明了为什么文档不显示实现System.Array
的IEnumerable<T>
在.NET Framework 2.0版中,Array类实现System.Collections.Generic.IList<T>
,System.Collections.Generic.ICollection<T>
和System.Collections.Generic.IEnumerable<T>
通用接口。这些实现是在运行时提供给数组的,因此对于文档构建工具而言是不可见的。因此,通用接口不会出现在Array类的声明语法中,并且没有接口成员的参考主题,这些参考成员只能通过将数组转换为通用接口类型来访问(显式接口实现)。将数组强制转换为这些接口之一时要注意的关键是,添加,插入或删除元素的成员会抛出NotSupportedException
。