我正在尝试创建一个值集合,每个值都对应一个操作。这样,我就可以在集合中搜索特定值,然后以通用方式调用关联的操作。
所以,这是我的第一次尝试:
public class CommandInfo
{
public string Name { get; set; }
public Action<RunArgument> Action { get; set; }
}
public class MyClass
{
public List<CommandInfo> Commands = new List<CommandInfo>
{
new CommandInfo { Name = "abc", Action = AbcAction } // <== ERROR HERE
};
public void AbcAction(RunArgument arg)
{
; // Do something useful here
}
}
在这种情况下,Commands
集合中新的 CommandInfo
的声明给出了错误:
A field initializer cannot reference the non-static field, method, or property 'MyNameSpace.MyClass.AbcAction(MyNameSpace.RunArgument)'
肯定有一种方法可以像这样存储对非静态方法的引用。有人可以帮帮我吗?
最佳答案
Surely there must be a way to store a reference to a non-static method like this. Can someone help me out?
有,只是不在字段初始值设定项中。所以这很好用:
public List<CommandInfo> Commands = new List<CommandInfo>();
public MyClass()
{
Commands.Add(new CommandInfo { Name = "abc",
Action = AbcAction });
}
... 或在构造函数中执行整个赋值。请注意,这实际上与委托(delegate)没有任何关系 - 这是偶然的,因为您实际上是在引用 this.AbcAction
。在其他任何方面,它都等同于这个问题:
public class Foo
{
int x = 10;
int y = this.x; // This has the same problem...
}
(当然,我希望你真的没有公共(public)领域...)
关于c# - 存储对非静态方法的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12808446/