5

我刚刚遇到以下代码(.NET 3.5),它看起来不应该编译给我,但它确实,并且工作正常:

bool b = selectedTables.Any(table1.IsChildOf));

Table.IsChildOf 实际上是一个具有以下签名的方法:

public bool IsChildOf(Table otherTable)

我认为这相当于:

bool b = selectedTables.Any(a => table1.IsChildOf(a));

如果是这样,正确的术语是什么?

4

3 回答 3

13

This is a method group conversion, and it's been available since C# 2. As a simpler example, consider:

public void Foo()
{
}

...

ThreadStart x = Foo;
ThreadStart y = new ThreadStart(Foo); // Equivalent code

Note that this is not quite the same as the lambda expression version, which will capture the variable table1, and generate a new class with a method in which just calls IsChildOf. For Any that isn't important, but the difference would be important for 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());
于 2011-03-10T10:45:09.637 回答
5

该表达式table1.IsChildOf称为方法组

你是对的,它是等价的,这确实是句法糖。

于 2011-03-10T10:38:17.860 回答
2

它被称为方法组。Resharper 鼓励这种代码。

于 2011-03-10T10:39:59.600 回答