2013-09-26 31 views
-4

我有這行代碼如何在C#中使用開關分割行代碼爲兩個

acctStatusLabel.Text = acct.acctStatusCode == "APPR" || acct.acctStatusCode == "IACT" 
             ? "Inactive" 
             : "Closed"; 

我需要做的是改變它,以便進近的StatusCode顯示「已認證」和IACT的StatusCode顯示 「無效」

這是完整的代碼集

if (acct.acctStatusCode == "DORM") 
      acctStatusLabel.Text = "Dormant"; 
     else 
      acctStatusLabel.Text = acct.acctStatusCode == "APPR" || acct.acctStatusCode == "IACT" 
             ? "Inactive" 
             : "Closed"; 
+1

[Switch reference](http://msdn.microsoft.com/en-us/library/vstudio/06tc147t.aspx) – Steve

+1

或者......你知道......你可以直接Google 。第一個結果:http://msdn.microsoft.com/en-us/library/06tc147t(v=vs.90).aspx – tnw

+0

新來c#不知道我在找什麼。感謝您的鏈接。 – TheDizzle

回答

4

喜歡這個?

switch(acct.acctStatusCode) 
{ 
    case "DORM": 
     acctStatusLabel.Text = "Dormant"; 
     break; 
    case "APPR": 
     acctStatusLabel.Text = "Approved"; 
     break; 
    case "IACT": 
     acctStatusLabel.Text = "Inactive"; 
     break; 
    default: 
     acctStatusLabel.Text = "Closed"; 
     break; 
} 

一個更好的選擇可能是使用靜態詞典:

{somewhere else} 
private static Dictionary<string, string> Codes = new Dictionary<string, string>(); 

{in static constructor} 
Codes.Add("DORM","Dormant"); 
Codes.Add("APPR","Approved"); 
Codes.Add("IACT","Inactive"); 

您的代碼會再是這樣的:

// set default value 
acctStatusLabel.Text = "Closed"; 
// lookup decoded value 
if(Codes.ContainsKey(code)) 
    acctStatusLabel.Text = Codes[code]; 

更好的辦法是把數據庫表或其他數據源中的代碼/解碼可以在不必重新編譯應用程序的情況下進行更改。

+0

謝謝你的幫助! – TheDizzle

1
switch(acct.acctStatusCode) 
{ 
    case "DORM": 
     acctStatusLabel.Text = "Dormant"; 
     break; 
    case "APPR": 
    case "IACT": 
     acctStatusLabel.Text = "Inactive"; 
     break; 
    default: 
     acctStatusLabel.Text = "Closed"; 
     break; 
} 
-1

只是做

if status =="xxxx" 
    text="XXXX" 
else if status == "yyy" 
    text = "YYY" 
else 
    text = "QQQ" 

我知道這是不是確切的代碼。我的意思是我建議不要試圖做出過於聰明的流動?和:等

0

像這樣的事情

switch(acct.acctStatusCode) { 
    case "DORM" : acctStatusLabel.Text = "Dormant"; break; 
    case "APPR" : case "IACT" : acctStatusLabel.Text = "Inactive"; break; 
    default : acctStatusLabel.Text = "Closed"; break; 
} 
2

這應該做的伎倆:

switch (acct.acctStatusCode) 
{ 
    case "DORM": 
     acctStatusLabel.Text = "Dormant"; 
     break; 
    case "APPR": 
     acctStatusLabel.Text = "Approved"; 
     break; 
    case "IACT": 
     acctStatusLabel.Text = "Inactive"; 
     break; 
    default: 
     acctStatusLabel.Text = "Closed"; 
} 

但是,你會好得多移動該邏輯進入acct對象本身。事情是這樣的:

public string StatusCodeText 
{ 
    get 
    { 
     switch (acctStatusCode) 
     { 
      case "DORM": 
       return "Dormant"; 
      case "APPR": 
       return "Approved"; 
      case "IACT": 
       return "Inactive"; 
     } 
     return "Closed"; 
    } 
} 

然後用它變得簡單了許多:

acctStatusLabel.Text = acct.StatusCodeText; 

「智能數據結構和愚蠢的代碼工作不是周圍的其他方法好了很多。」 - Eric S. Raymond

+0

非常感謝! – TheDizzle