【IT168技术文档】
最后,Lambda 表达式支持更冗长的语法,允许您显式指定类型,以及执行多条语句。例如:
return EnumerableExtensions.Where(customers,(Customer c) => { int zip = zipCode; return c.ZipCode == zip; });
好消息是,我们向原始文章中提议的理想语法迈进了一大步,并且我们能够利用一个通常能在查询运算符以外发挥作用的语言功能来实现这一目标。让我们再次看一下我们目前所处的阶段:
IEnumerable locals =EnumerableExtensions.Where(customers, c => c.ZipCode == 91822);
这里存在一个明显的问题。客户目前必须了解此 EnumerableExtensions 类,而不是考虑可在 Customer 上执行的操作。另外,在多个运算符的情况下,使用者必须逆转其思维以编写正确的语法。例如:
IEnumerable locals =EnumerableExtensions.Select( EnumerableExtensions.Where(customers, c => c.ZipCode == 91822),c => c.Name);
sequence locals =customers.where(ZipCode == 98112).select(Name);
因此,是否可利用另一种语言功能来进一步接近实现理想语法呢?
扩展方法
结果证明,更好的语法将以被称为扩展方法的语言功能形式出现。扩展方法基本上属于可通过实例语法调用的静态方法。上述查询问题的根源是我们试图向 IEnumerable 添加方法。但如果我们要添加运算符,如 Where、Select 等,则所有现有和未来的实现器都必须实现那些方法。尽管那些实现绝大多数都是相同的。在 C# 中共享“接口实现”的唯一方法是使用静态方法,这是我们处理以前使用的 EnumerableExtensions 类的一个成功方法。
假设我们转而将 Where 方法编写为扩展方法。那么,查询可重新编写为:
IEnumerable locals =customers.Where(c => c.ZipCode == 91822);
public static IEnumerable Where(this IEnumerable items, Func<T, bool> predicate)
interface IDog { // Barks for 2 seconds void Bark(); void Bark(int seconds); }