更有效地编写开关

use*_*470 0 c# switch-statement

我目前有一段代码如下:

switch (objectname)
{
    case "objectbla":
        DoSomething(1, objectName, someOtherVar);
         break;
    case "objectblabla":
        DoSomething(2, objectName, someOtherVar);
        break;
    case "objectetc":
        DoSomething(3, objectName, someOtherVar);
        break;
    case "objectanother":
        DoSomething(4, objectName, someOtherVar);
        break;
    case "objectobj":
        DoSomething(5, objectName, someOtherVar);
        break;
    default:
        break;
}
Run Code Online (Sandbox Code Playgroud)

现在,看看这个开关是多么重复,只有第一个参数计数一次,我相信这可以更有效地编写.不过我不确定.写这个更好的方法是什么?

pok*_*oke 6

如果第一个参数是唯一不同的东西objectname,你应该考虑使用字典:

// you only have to set this up once
var lookup = new Dictionary<string, int>()
{
    ["objectbla"] = 1,
    ["objectblabla"] = 2,
    ["objectetc"] = 3,
    ["objectanother"] = 4,
    ["objectobj"] = 5,
};


// actual logic
if (lookup.TryGetValue(objectname, out var objectId))
{
    DoSomething(objectId, objectName, someOtherVar);
}
else
{
    // objectname is not in the lookup dictionary
}
Run Code Online (Sandbox Code Playgroud)

这是一般的想法.根据查找的外观,您也可以选择不同的解决方案,但字典是最冗长但最灵活的方式.