Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将静态方法分配给System.Delegate对象?_C#_Static_Delegates - Fatal编程技术网

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

C# 如何将静态方法分配给System.Delegate对象?,c#,static,delegates,C#,Static,Delegates,我的问题是,我有一个类,它的构造函数以System.Delegate对象作为参数,我不知道如何将方法分配给System.Delegate对象。 这是我现在掌握的密码 class TestClass { Delegate c = TestMetod; static void TestMetod() { MessageBox.Show("it worked !"); } } 但这不起作用,因为很奇怪,System.Delegate是msdna所述的非

我的问题是,我有一个类,它的构造函数以System.Delegate对象作为参数,我不知道如何将方法分配给System.Delegate对象。 这是我现在掌握的密码

class TestClass
{
    Delegate c = TestMetod;
    static void TestMetod()
    {
        MessageBox.Show("it worked !");
    }
}
但这不起作用,因为很奇怪,System.Delegate是msdna所述的非委托类型。
既然无法“将方法组TestMetod分配给非委托类型‘System.delegate’”

静态方面并不是这里的核心问题,我该如何做我需要的事情呢。您需要一个(任意)委托来捕获TestMethod,然后可以将其分配给System.delegate。您可以使用
操作
作为这样的中介

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

成功了!但是有没有办法避免使用操作?@user1909612当然,只需使用现有的任何其他委托即可。
Action
没有什么特别之处,但是您需要使用某种类型的委托。
Action()
只是匹配
void TestMethod()
的最简单方法。我会使用
delegate c=newaction(TestMethod)
而不是引入一个helper字段。