Using delegates with non static methods [no picked

2019-07-16 14:37发布

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).

标签: delegates
2条回答
smile是对你的礼貌
2楼-- · 2019-07-16 14:42

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");
    }
}
查看更多
地球回转人心会变
3楼-- · 2019-07-16 14:56

How about TestDelegate testDelgate = MyMethod;

查看更多
登录 后发表回答