繁体   English   中英

使用委托、静态方法和多播将函数作为参数传递

[英]Passing functions as arguments using delegates, static methods and multicasting

我一直在研究 C# 委托,并且从 Python 的角度我想知道如果我将静态方法视为一等公民并直接将其作为 arg 传递而不包装在委托类型中会发生什么。

令人惊讶的是,它似乎奏效了。 但是,当尝试对多播使用相同的方法时,它失败了:

[CS0019] Operator '+' cannot be applied to operands of type 'method group' and 'method group'

我的问题是幕后发生了什么以允许我直接将staticMethod作为参数传递,为什么同一个过程不允许我以与使用委托类型可以实现的方式类似的方式直接多播该方法?

using System;

namespace Delegates
{
    class Program
    {
        public delegate void Func();

        public static void staticMethod()
        {
            Console.WriteLine("In staticMethod()");
        }
        
        public static void executeFunc(Func f)
        {
            f();
        }
        
        static void Main(string[] args)
        {
            Func f = staticMethod;
            
            executeFunc(f);
            
            // why cant' we just pass the static method as a first-class citizen and bypass any delegate creation?'
            executeFunc(staticMethod); // we can - this works
            
            executeFunc(f + f);
            executeFunc(staticMethod + staticMethod); // but this doesn't
        }
    }
}

可能是某种隐式转换,因为以下似乎有效:

executeFunc((Func)staticMethod + (Func)staticMethod);

当您将Func定义为委托时,它变成了System.MultiCastDelegate为其定义了运算符 +。 编辑:ahum,编译器开启加入到Delegate.Combine ,描述在这里

您的静态方法只是一个普通函数,即method group 并且没有为method group类型定义加法运算。 (它会做什么?)

通过键入executeFunc((Func)staticMethod + (Func)staticMethod); 您正在将方法组类型显式转换为委托类型……并且编译器知道要再次做什么。

编辑:顺便说一下,请注意System.Action的存在,它是您的Func的库。

暂无
暂无

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

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