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

时间:2013-04-26 15:22:35

标签: c# static delegates

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

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

但这不起作用,因为奇怪的是,System.Delegate是一个非委托类型,如msdna所述。 我怎么应该做我需要的,因为不可能“将方法组TestMetod分配给非委托类型'System.Delegate'”

1 个答案:

答案 0 :(得分:5)

static方面不是核心问题。您需要一个(任何)委托来捕获TestMethod,然后您可以将其分配给System.Delegate。您可以使用Action作为此类中间人。

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