tom*_*ing 5 c# lambda syntactic-sugar
我刚刚遇到以下代码(.NET 3.5),它看起来不应该编译给我,但确实如此,并且工作正常:
bool b = selectedTables.Any(table1.IsChildOf));
Run Code Online (Sandbox Code Playgroud)
Table.IsChildOf实际上是一个具有以下签名的方法:
public bool IsChildOf(Table otherTable)
Run Code Online (Sandbox Code Playgroud)
我认为这相当于:
bool b = selectedTables.Any(a => table1.IsChildOf(a));
Run Code Online (Sandbox Code Playgroud)
如果是这样,那么适当的术语是什么?
Jon*_*eet 13
这是一个方法组转换,它从C#2开始就可用.作为一个更简单的例子,请考虑:
public void Foo()
{
}
...
ThreadStart x = Foo;
ThreadStart y = new ThreadStart(Foo); // Equivalent code
Run Code Online (Sandbox Code Playgroud)
请注意,这与lambda表达式版本不完全相同,后者将捕获变量 table1,并使用仅调用的方法生成新类IsChildOf.对于Any不是很重要,但差异会为重要Where:
var usingMethodGroup = selectedTables.Where(table1.IsChildOf);
var usingLambda = selectedTables.Where(x => table1.IsChildOf(x));
table1 = null;
// Fine: the *value* of `table1` was used to create the delegate
Console.WriteLine(usingMethodGroup.Count());
// Bang! The lambda expression will try to call IsChildOf on a null reference
Console.WriteLine(usingLambda.Count());
Run Code Online (Sandbox Code Playgroud)
该表达式table1.IsChildOf称为方法组.
你是对的,它是等价的,这确实是语法糖.
| 归档时间: |
|
| 查看次数: |
1056 次 |
| 最近记录: |