使用具有非静态方法的委托[没有选择的答案] [英] Using delegates with non static methods [no picked answer]
问题描述
我非常有信心,我应该能够使用具有非静态方法的委托,但以下内容会给我一个错误:
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");
}
}
我得到的错误是:
字段初始化器无法引用非静态字段,方法或
属性
A field initializer cannot reference the non-static field, method, or property
如果我将MyMethod设为静态,则一切正常。我以为我可以将委托与非静态方法一起使用是我的错吗(我确信我以前记得这样做)。
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).
推荐答案
回答这个问题,因为我不得不显示更多评论并做了两次尝试,然后才意识到实际的答案是什么。
Answering this as I had to 'show more comments' and do a double take before I realised what the actual answer was.
错误:
字段初始化器无法引用非静态字段,方法或
属性
A field initializer cannot reference the non-static field, method, or property
解决方案是在构造函数内部初始化委托。
The solution is to initialise the delegate inside the constructor.
我在C#语言参考本身中找不到它,
I couldn't actually find this in the C# Language Reference itself, and a lot of the stock examples are static methods.
ie
public class TestClass
{
private delegate void TestDelegate();
TestDelegate testDelegate;
public TestClass()
{
testDelegate = new TestDelegate(MyMethod);
}
private void MyMethod()
{
Console.WriteLine("Foobar");
}
}
这篇关于使用具有非静态方法的委托[没有选择的答案]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!