更有效地编写交换机

时间:2017-10-04 13:23:02

标签: 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;
}

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

4 个答案:

答案 0 :(得分: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
}

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

答案 1 :(得分:1)

如果必须是switch,那该怎么做:

int  aNumber;
switch (objectname)
{
    case "objectblabla":
        aNumber = 1
        break;
    case "objectetc":
        aNumber = 2
        break;
    case "objectanother":
        aNumber = 3
        break;
    case "objectobj":
        aNumber = 4
        break;
    default:
        break;
}

DoSomething(aNumber, objectName, someOtherVar);

如果没有:

string[] ListOfObjectNames = { "objectblabla", "objectetc", "objectanother" };
DoSomething(Array.IndexOf(ListOfObjectNames, objectname), objectName, someOtherVar);

答案 2 :(得分:1)

你是对的,有更好的方法。 如果您创建一个静态字典作为查找表,那么您可以使用它来获取您的幻数。

static Dictionary<string, int> lookup= new Dictionary<string, int>()
{
    { "objectbla",1},
    {"objectblabla", 2},
  etc.
};

然后你的职能部门变成:

DoSomething(lookup[objectname], objectName, someOtherVar);

您还应该添加代码以考虑使用无效密钥的可能性,否则,它会抛出异常。

答案 3 :(得分:1)

我选择了enum方法。

__doPostBack('Button2', '');
相关问题