delegate void Dele(string str);
delegate void Alli(int num);
class Program
{
static void Main(string[] args)
{
Dele dele = Test; // O
Alli alli = Test; // X
}
static void Test(object obj) { }
}
Alli alli = 测试;//X
为什么???
也许……
str 作为对象
( O )
num 作为对象
( X )
???
(对不起,我英语不好)
(看起来您的帖子主要是代码;请添加更多详细信息。:好的)
最佳答案
此行为在 C# 语言规范中指定。
这里:
Dele dele = Test;
你正在做一个 method group conversion .允许方法组转换的要求之一是
The selected method M must be compatible (Delegate compatibility) with the delegate type D, or otherwise, a compile-time error occurs.
Delegate compatibility是这样指定的(强调我的):
A method or delegate M is compatible with a delegate type D if all of the following are true:
- D and M have the same number of parameters, and each parameter in D has the same ref or out modifiers as the corresponding parameter in M.
- For each value parameter (a parameter with no ref or out modifier), an identity conversion (Identity conversion) or implicit reference conversion (Implicit reference conversions) exists from the parameter type in D to the corresponding parameter type in M.
- For each ref or out parameter, the parameter type in D is the same as the parameter type in M.
- An identity or implicit reference conversion exists from the return type of M to the return type of D.
是从string
到object
的隐式引用转换,因为string
是的子类>object
,但是没有从int
到object
的隐式引用转换。 int
是一个值类型,所以转换实际上是一个装箱转换。因此,方法组转换不适用于Alli
和Test
。
关于C# 委托(delegate)参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58110326/