C# 委托(delegate)参数类型

标签 c# delegates

    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.

stringobject的隐式引用转换,因为string的子类>object,但是没有intobject 的隐式引用转换。 int 是一个值类型,所以转换实际上是一个装箱转换。因此,方法组转换不适用于AlliTest

关于C# 委托(delegate)参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58110326/

相关文章:

c# - 委托(delegate)给实例方法不能有 null 'this'

objective-c - Objective-C - 设置 UIPickerView 委托(delegate)

c# - List.Sort 使用 lambda 表达式

c# - ASP.NET Identity - 不支持每种类型的多个对象集

c# - 使用 ComVisible(false) 时指定 Guid 有什么意义吗?

c# - 与 FK 的一对一关系不同于 PK

C# 使用 BlockingCollection 正确中止始终运行的线程

ios - 如何在 SwiftUI 中实现自定义委托(delegate)

swift - 对象初始化后是否立即调用事件?

c# - 具有定义大小的特殊队列