C# 委托参数类型
C# delegate argument type
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 = Test; // X
为什么???
也许……
str as object
( O )
num as object
( X )
???
(对不起,我英语不好)
(看起来你的 post 主要是代码;请添加更多详细信息。:好的)
此行为在 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
.
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 = Test; // X
为什么???
也许……
str as object
( O )
num as object
( X )
???
(对不起,我英语不好)
(看起来你的 post 主要是代码;请添加更多详细信息。:好的)
此行为在 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
.