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

本文关键字:静态 字典 实例方法 包含 | 更新日期: 2023-09-27 18:05:13

我有一个像这样的大开关语句的方法:

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);
}

我看到的问题是,一个新的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);
}

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

可以在静态构造函数中初始化它-但是您需要创建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 == "";
    }
}

在理论上,我相信它应该是可行的,没有lambda表达式创建一个"开放委托",但它将需要更多的工作使用反射。如果您不介意额外间接的丑陋和微小的性能损失,我认为这种方法应该工作得很好。