【发布时间】:2019-12-07 22:25:03
【问题描述】:
我刚刚开始学习 LINQ。以下示例使用Where,它是标准查询运算符之一。
string[] names = { "Tom", "Dick", "Harry" };
IEnumerable<string> filteredNames = System.Linq.Enumerable.Where(names, n => n.Length >= 4);
我对它的工作原理做了一些研究,发现this source:
public static partial class Enumerable
{
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) {
if (source == null) throw Error.ArgumentNull("source");
if (predicate == null) throw Error.ArgumentNull("predicate");
if (source is Iterator<TSource>) return ((Iterator<TSource>)source).Where(predicate);
if (source is TSource[]) return new WhereArrayIterator<TSource>((TSource[])source, predicate);
if (source is List<TSource>) return new WhereListIterator<TSource>((List<TSource>)source, predicate);
return new WhereEnumerableIterator<TSource>(source, predicate);
}
/* ... */
}
我不明白为什么它的第一个参数this IEnumerable<TSource> source 以this 关键字为前缀。我知道扩展方法允许使用新方法扩展现有类型,而无需
改变原始类型的定义和类型
第一个参数将是扩展的类型。
你能解释一下下面的逻辑吗?
【问题讨论】:
-
你是在问为什么 C#语言要求你写
this来定义扩展方法? -
非静态方法的实现使得每个方法调用都有一个隐藏参数。所以每一个非静态方法都可以想象成一个静态方法,加上一个额外的参数:
this。因此,在扩展方法中将一个参数声明为this是有意义的。这是一个完美的关键字。 -
好吧,编译器需要某种方式来将此函数解释为扩展方法。这是由该语法完成的。为什么是
this而不是例如default?怎么会有人知道? -
@CorentinPane no.