什么是C#中的方法组?方法

2023-09-02 10:15:20 作者:拼命十三妹

我也经常遇到的错误,如在案件,从方法组到串不能转换,如:

I have often encountered an error such as "cannot convert from 'method group' to 'string'" in cases like:

var list = new List<string>();
// ... snip
list.Add(someObject.ToString);

当然,

有一个错字的最后一行,因为我忘了在调用括号的ToString 。正确的形式是:

of course there was a typo in the last line because I forgot the invocation parentheses after ToString. The correct form would be:

var list = new List<string>();
// ... snip
list.Add(someObject.ToString()); // <- notice the parentheses

不过我来不知道什么是方法组。 Google是没有太大的帮助,也不 MSDN 。

However I came to wonder what is a method group. Google isn't much of a help nor MSDN.

推荐答案

方法组是对的的一套方法的名称的(这可能只是一个) - 即理论上的的ToString 方法可以有多个重载(加任何扩展方法):的ToString()的ToString(字符串格式)等 - 因此的ToString 本身是一种方法组

A method group is the name for a set of methods (that might be just one) - i.e. in theory the ToString method may have multiple overloads (plus any extension methods): ToString(), ToString(string format), etc - hence ToString by itself is a "method group".

这通常可以转换方法组到(类型)代表通过使用重载 - 而不是一个字符串等;它没有意义。

It can usually convert a method group to a (typed) delegate by using overload resolution - but not to a string etc; it doesn't make sense.

一旦添加了括号,再一次;重载踢,你已经清楚地确定了一个方法调用。

Once you add parentheses, again; overload resolution kicks in and you have unambiguously identified a method call.