2017-10-04 60 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);