简体   繁体   English

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
Why???为什么???

Maybe...也许...
str as object ( O ) str as object ( O )
num as object ( X ) num as object ( X )
??? ???

(Sorry, I'm not good at English) (对不起,我英语不好)
(It looks like your post is mostly code; please add some more details.: OK) (看起来你的帖子主要是代码;请添加更多细节。:好的)

This behaviour is specified in the C# language specification.此行为在 C# 语言规范中指定。

Here:这里:

Dele dele = Test;

You are doing a method group conversion .您正在进行方法组转换 One of the requirements for a method group conversion to be allowed is that允许方法组转换的要求之一是

The selected method M must be compatible (Delegate compatibility) with the delegate type D, or otherwise, a compile-time error occurs.选择的方法 M 必须与委托类型 D 兼容(委托兼容性),否则会发生编译时错误。

Delegate compatibility is specified like this (emphasis mine): 委托兼容性是这样指定的(强调我的):

A method or delegate M is compatible with a delegate type D if all of the following are true:如果满足以下所有条件,则方法或委托 M 与委托类型 D 兼容:

  • 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. D 和 M 具有相同数量的参数,并且 D 中的每个参数与 M 中的相应参数具有相同的 ref 或 out 修饰符。
  • 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.对于每一个值参数(没有 ref 或 out 修饰符的参数),从 D 中的参数类型到 M 中对应的参数类型都存在一个身份转换(Identity conversion)或隐式引用转换(Implicit reference conversions)。
  • For each ref or out parameter, the parameter type in D is the same as the parameter type in M.对于每个 ref 或 out 参数,D 中的参数类型与 M 中的参数类型相同。
  • An identity or implicit reference conversion exists from the return type of M to the return type of D.从 M 的返回类型到 D 的返回类型存在标识或隐式引用转换。

There is an implicit reference conversion from string to object , because string is a subclass of object , but there isn't an implicit reference conversion from int to object .存在stringobject的隐式引用转换,因为stringobject的子类,但没有intobject的隐式引用转换。 int is a value type, so the conversion is actually a boxing conversion . int是一个值类型,所以转换实际上是一个装箱转换 Therefore, the method group conversion does not work for Alli and Test .因此,方法组转换不适用于AlliTest

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM