C#中的方法组是什么? [英] What is a method group in C#?
问题描述
我经常遇到诸如无法从'方法组'转换为'字符串'"之类的错误,例如:
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(string format)
等 - 因此 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.
这篇关于C#中的方法组是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!