如何使用字典将字符串映射到方法

5
我有一些代码看起来像这样:
switch(SomeString)
{
   case "Value1":
        MethodA();
        break;

   case "Value2":
        MethodB();
        break;
   ... 40 other cases
}

如何使用一个<string, method>的字典重写这段代码,使得例如键为"Value1",值为MethodA(),并且我要写一些东西来表达"执行名称为SomeString值的键的函数"。请注意,所有方法都不带参数,并且没有任何返回值。

请访问以下链接以查看与C#重构switch相关的问题:http://stackoverflow.com/search?q=[c%23]+refactor+switch - Alexei Levenkov
2个回答

11

你可以这样做:

var actions = new Dictionary<string, Action>()
{
    { "Value1", () => MethodA() },
    { "Value2", () => MethodB() },
};

您可以像这样调用:

actions["Value1"]();

现在你可以简化为这样:

var actions = new Dictionary<string, Action>()
{
    { "Value1", MethodA },
    { "Value2", MethodB },
};

但我建议选择第一个选项,因为它让你可以做到这一点:

var hello = "Hello, World!";
var actions = new Dictionary<string, Action>()
{
    { "Value1", () => MethodA(42) },
    { "Value2", () => MethodB(hello) },
};

刚好我在想委托和 Lambda 表达式。 - Rayshawn
附注:如果遵循 () => MethodB(hello) 的建议,请非常小心 - C# 捕获变量,而不是值 - 因此,如果 hello 有所更改,则对 MethodB 的调用也会发生更改。 - Alexei Levenkov
好的,谢谢你的回答;这个概念与我在JavaScript中写的答案非常相似http://stackoverflow.com/questions/17076429/why-is-this-simple-function-not-working/17078580#17078580 只是不知道如何在C#中使其工作!谢谢! - frenchie

3

声明你的字典:

Dictionary<string,Action> methodMap = new Dictionary<string,Action>();;

添加条目:

methodMap["Value1"] = MethodA; ...

执行:

methodMap["Value1"] ();


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接