我有一个像这样的巨大的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) {...}
Run Code Online (Sandbox Code Playgroud)
现在我想用代理字典替换它,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);
}
Run Code Online (Sandbox Code Playgroud)
我看到的问题是,新的Dictionary被实例化并填充了MyClass的每个新实例.
是否有可能以某种方式使该Dictionary(包含实例方法的委托)成为一个静态成员,它只能在静态构造函数中初始化一次?
像这样的事情(不起作用):
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);
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 19
您可以在静态构造函数中初始化它 - 但是您需要创建MyClass可能不是您想要的实例,因为我假设您希望命令在" Execute已调用的实例的上下文中"执行.
或者,您可以使用代理来填充字典,代理也可以使用MyClass以下代码:
class MyClass
{
static Dictionary<string, Func<MyClass, string, bool>> commands
= new Dictionary<string, Func<MyClass, string, bool>>
{
{ "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 == "";
}
}
Run Code Online (Sandbox Code Playgroud)
从理论上讲,我认为通过创建"开放委托"而没有lambda表达式应该是可行的,但是使用反射需要更多的工作.如果你不介意额外间接的丑陋和微小的性能损失,我认为这种方法应该工作得很好.
| 归档时间: |
|
| 查看次数: |
2407 次 |
| 最近记录: |