2017-10-04 34 views
0

我现在有一段代码,看起来像这样:写开关更有效地

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

现在,眼看这个开关是如何重复的,只有第一个参数一次计数,我敢肯定,这可能写得更有效率。不过,我不确定。什么会是一个更好的方式来写这个?

+2

那么,如果'objectname'是一个'enum',枚举的值可以被传递到'DoSomething的((INT)yourEnumValue,对象名,someOtherVar);' – DiskJunky

+3

把你所有的字符串的字典词典''并做一个单独的调用'DoSomething(dict [objectname],objectName,someOtherVar)' –

+2

或'Array.IndexOf(stringArray,objectname)+ 1' –

回答

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 
} 

这是一般的想法。取决于你的查找的样子,你也可以选择不同的解决方案,但字典是最详细的,但也是最灵活的方法来做到这一点。

+0

不错的捅,你做得很好 –

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

你是正确的,有一个更好的办法。 如果您创建一个静态字典作为查找表,然后您使用它来获得你的幻数。

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

那么你的函数体变为:

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

您还应该添加代码,考虑到正在使用无效键的可​​能性,否则,因为它代表它会抛出一个异常。

1

我想用enum方法。

enum objects 
{ 
    objectbla = 1, 
    objectblabla, 
    objectetc, 
    objectanother, 
    objectobj 
}; 

DoSomething((int)Enum.Parse(typeof(objects), objectName), objectName, someOtherVar);