简体   繁体   中英

how do i assign a static method to a System.Delegate object?

My problem is that i have a class whose constructor takes a System.Delegate object as a parameter and i have no idea how to assign a method to a System.Delegate object. This is the code i have right now

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

but that doesn' t work because, oddly enough, System.Delegate is a non-delegate type as stated by msdna. How am i supposed to do what i need since it is impossible to "assign method group TestMetod to non-delegate type 'System.Delegate'"

The static aspect is not the core issue here. You need a (any) delegate to capture TestMethod and then you can assign that to a System.Delegate. You can use Action as such an intermediate.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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