包含实例方法委托的静态字典

我有一个像这样的巨大的switch语句这个方法:

public bool ExecuteCommand(string command, string args) { bool result = false; switch (command) { case "command1": result = Method1(args); break; case "command2": result = Method2(args); break; // etc. } return result; } private bool Method1(string args) {...} 

现在我想用Func委托的字典替换它,这样我就可以消除switch语句:

 private Dictionary<string, Func> _commands = new ...; public MyClass() { _commands.Add("command1", Method1); // etc: } public bool ExecuteCommand(string command, string args) { return _commands[command](args); } 

我看到的问题是,新的Dictionary被实例化并填充了MyClass的每个新实例。

是否有可能以某种方式使该Dictionary(包含实例方法的委托)成为一个静态成员,它只能在静态构造函数中初始化一次?

像这样的事情(不起作用):

 private static Dictionary<string, Func> _commands = new ...; static MyClass() { // the following line will result in a compiler error: // error CS0120: An object reference is required for the non-static field, // method, or property 'MyClass.Method1(string, string)' _commands.Add("command1", MyClass.Method1); } 

可以在静态构造函数中初始化它 – 但是您需要创建MyClass实例,这可能不是您想要的,因为我假设您希望命令在“已Execute的实例的上下文中” Execute上。

或者,您可以使用代理来填充字典,代理也可以使用MyClass实例,如下所示:

 class MyClass { static Dictionary> commands = new Dictionary> { { "Foo", (@this, x) => @this.Foo(x) }, { "Bar", (@this, y) => @this.Bar(y) } }; public bool Execute(string command, string value) { return commands[command](this, value); } public bool Foo(string x) { return x.Length > 3; } public bool Bar(string x) { return x == ""; } } 

从理论上讲,我认为通过创建一个“开放委托”,没有lambda表达式应该是可行的,但是使用reflection需要更多的工作。 如果你不介意额外间接的丑陋和微小的性能损失,我认为这种方法应该很好。