我有一个带有巨大 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<string, bool>> _commands = new ...;
public MyClass()
{
_commands.Add("command1", Method1);
// etc:
}
public bool ExecuteCommand(string command, string args)
{
return _commands[command](args);
}
我看到的问题是,一个新的字典被实例化并填充了 MyClass 的每个新实例。
是否有可能以某种方式使该字典(包含实例方法的委托)成为静态成员,在静态构造函数中仅初始化一次?
例如。像这样的东西(不起作用):
private static Dictionary<string, Func<string, bool>> _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);
}