Using delegates with non static methods [no picked answer]

南笙酒味 提交于 2019-12-24 06:26:18

问题


I am pretty confident that I should be able to use a delegate with a non-static method, but the below is giving me an error:

public class TestClass
{
    private delegate void TestDelegate();
    TestDelegate testDelegate = new TestDelegate(MyMethod);

    private void MyMethod()
    {
        Console.WriteLine("Foobar");
    }
}

The error I am getting is:

A field initializer cannot reference the non-static field, method, or property

If I make MyMethod static, everything works fine. Was I simply wrong in thinking I could use a delegate with a non static method (I am sure I remember doing so in the past).


回答1:


Answering this as I had to 'show more comments' and do a double take before I realised what the actual answer was.

Error:

A field initializer cannot reference the non-static field, method, or property

The solution is to initialise the delegate inside the constructor.

I couldn't actually find this in the C# Language Reference itself, and a lot of the stock examples are static methods.

i.e.

public class TestClass
{
    private delegate void TestDelegate();
    TestDelegate testDelegate;

    public TestClass()
    {
        testDelegate = new TestDelegate(MyMethod);
    }

    private void MyMethod()
    {
        Console.WriteLine("Foobar");
    }
}



回答2:


How about TestDelegate testDelgate = MyMethod;



来源:https://stackoverflow.com/questions/14860002/using-delegates-with-non-static-methods-no-picked-answer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!