2013-05-21 49 views
-1

我正在開發我的C#項目, ,我需要這樣做,但不需要If;每個字符串函數(IDK它是怎麼被調用的)

for (String = n) do that 
for (String = s) do those 
for (String = c) do this 

我不知道它是如何調用,或如何做到這一點不長If功能。

+4

'之開關? http://msdn.microsoft.com/en-us/library/06tc147t(v=vs.80).aspx –

+0

沒有使用'if else if else'條件語句會有什麼邏輯原因? –

+0

您可能不希望首先使用「字符串」。向前跳,如果'String'是一個'Action',你可以調用它。 – Jodrell

回答

2

可以簡單地使用switch語句:

switch (myString) { 
    case "n": 
     //... 
     break; 
    case "s": 
     //... 
     break; 
    case "c": 
     //... 
     break; 
} 

但要注意,使用的case -strings是常數區分大小寫
請注意,使用myString.ToLower()是危險的!

如果案例sensivity是一個問題,你必須使用if S:

if (string.Compare(myString, "abc", true)==0)) { 
    //... 
} 
else if (string.Compare(myString, "123", true)==0)) { 
    //... 
} 
+0

「字符串是......不區分大小寫」(原文如此)。你能否支持這個聲明? C#**使用'=='進行字符串比較時區分大小寫,'switch'爲[no](http://stackoverflow.com/questions/2334134/how-to-make-the-c-sharp- switch-statement-use-ignorecase)[different](http://stackoverflow.com/questions/5986694/cs-switch-statement-is-case-sensitive-is-there-a-way-to-toggle-it-所以它becom) –

+0

@AndyBrown:對不起,我的壞! – joe

+0

謝謝!這是我正在尋找的^ _ ^ –

1

您可以使用switch,例如,一個叫myString變量:

switch (myString) { 
    case "n": 
    doThat(); 
    break; 
    case "s": 
    doThose(); 
    break; 
    case "c": 
    doThis(); 
    break; 
    default: 
    doNothing(); 
    break; 
} 

default的情況是存在的情況下,你的myString是沒有你在你的具體case語句所考慮的值。

+0

相同喬說...謝謝! –

+0

@ TDT-Alpha。哈哈,除了我首先回答;) –

+0

它是如此預測(非盟,我的運氣和信仰是這樣的情況下)。謝謝你們兩個! –

相關問題