c# - 如何将静态方法分配给 System.Delegate 对象?

标签 c# static delegates

我的问题是,我有一个类,其构造函数采用 System.Delegate 对象作为参数,但我不知道如何将方法分配给 System.Delegate 对象。 这是我现在拥有的代码

class TestClass
{
    Delegate c = TestMetod;
    static void TestMetod()
    {
        MessageBox.Show("it worked !");
    }
}

但这不起作用,因为奇怪的是,System.Delegate 是 msdna 所声明的非委托(delegate)类型。 我应该如何做我需要的事情,因为不可能“将方法组 TestMetod 分配给非委托(delegate)类型'System.Delegate'”

最佳答案

静态方面不是这里的核心问题。您需要一个(任何)委托(delegate)来捕获 TestMethod,然后您可以将其分配给 System.Delegate。您可以使用 Action 作为这样的中间体。

class TestClass
{
    static Action a = TestMetod;
    static Delegate c = a;
    static void TestMetod()
    {
        MessageBox.Show("it worked !");
    }
}

关于c# - 如何将静态方法分配给 System.Delegate 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16239922/

相关文章:

cocoa - 为什么我要制定一个全可选的消息协议(protocol)?

c# - 编译器歧义调用错误-具有Func <>或Action的匿名方法和方法组

ios - Swift ViewController,objective C 协议(protocol),类型 'ViewController' 不符合协议(protocol) 'MyProtocolDelegate'

c# - 控制台编程中的上划线

c++ - 为什么需要在初始化时指定外部/静态变量的类型?

objective-c - 拥有应用程序范围阵列的最佳方式?

c - C 中 const static struct 对象的安全性

c# - 通过委托(delegate)和事件调用的区别 C#

c# - 从 DateTimeOffset 中删除时区偏移量?

c# - 什么是 '' Size''参数大小单位,在Set parameter Method中?