在资源文件中使用'switch'和字符串

rkg*_*rkg 15 .net c# embedded-resource switch-statement

我的资源(.resx)文件中有一堆字符串.我试图直接使用它们作为switch语句的一部分(请参阅下面的示例代码).

class Test
{
    static void main(string[] args)
    {
        string case = args[1];
        switch(case)
        {
            case StringResources.CFG_PARAM1: // Do Something1 
                break;
            case StringResources.CFG_PARAM2: // Do Something2
                break;
            case StringResources.CFG_PARAM3: // Do Something3
                break;              
            default:
                break;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我看了一些解决方案,其中大多数似乎都暗示我需要将它们声明为const string我个人不喜欢的.我喜欢这个问题的最高投票解决方案:在switch语句中使用字符串集合.但后来我需要确保我enumstrings资源文件绑在一起.我想知道一个巧妙的方法.

编辑:在研究如何使用时 也找到了这个很好的答案Action:

xan*_*tos 25

你可以用一个Dictionary<string, Action>.您Action为Dictionary中的每个字符串放置一个(一个方法的委托)并搜索它.

var actions = new Dictionary<string, Action> {
    { "String1", () => Method1() },
    { "String2", () => Method2() },
    { "String3", () => Method3() },
};

Action action;

if (actions.TryGetValue(myString, out action))
{
    action();
}
else
{
    // no action found
}
Run Code Online (Sandbox Code Playgroud)

作为旁注,如果Method1已经是一个Action或一个void Method1()方法(没有参数,没有返回值),你可以这样做

    { "String1", (Action)Method1 },
Run Code Online (Sandbox Code Playgroud)


Fre*_*örk 9

你不能这样做.编译器必须能够评估值,这意味着它们需要是文字或常量.