2011-04-15 56 views
0

我有了下面的代碼的程序:使此代碼片斷更好

foreach (string section in DataAccessLayer.AcceptedSections) 
{ 
    switch (section) 
    { 
     case "Section1": 
      Console.WriteLine("Section 1"); 
      break; 
     case "Section2": 
      Console.WriteLine("Section 2"); 
      break; 
     case "Section3": 
      Console.WriteLine("Section 3"); 
      break; 
     default: 
      Console.WriteLine("Default section"); 
      break; 
    }      
} 

有反正我能做到這一點的代碼做什麼,而不情況下,內再次提供了部分的字符串? DataAccessLayer.AcceptedSections是動態的,我不希望爲我的代碼添加另一部分案例,每次新章節出現時都會重新編譯和重新部署。這是星期五,我的思想不太好。

例如: 我不想添加以下代碼,當第4節被添加到數據庫中:

case "Section4": 
    Console.WriteLine("Section 4"); 
    break; 
+0

那麼你的'Accepte自定義屬性dSections'表看起來像? – hunter 2011-04-15 19:05:27

+0

屬於CodeReview.StackExchange.Com – 2011-04-15 19:06:23

+0

他們都是很好的答案,我對所有答案都+1,但對於我的情況,字典工作得最好,因爲我能夠附加我想要執行的方法。 – capdragon 2011-04-15 19:36:42

回答

3

有由section鍵控Dictionary<string,Action<T>>。這將完全取代switch語句。

調用相應的動作:

foreach (string section in DataAccessLayer.AcceptedSections) 
{ 
    myActionsDictionary[section](); 
} 
+0

@Downvoter - 謹慎評論? – Oded 2011-04-15 19:08:17

+0

真的嗎?投票?這不是一個不錯的選擇,雖然它不是動態的。 +1 – hunter 2011-04-15 19:08:50

+1

a)我不是downvoter。 b)然而,這是否仍然存在與以前相似的挑戰?您仍然需要看到「第4部分」,並在字典中註冊了適當的操作。 – 2011-04-15 19:10:03

5

如果字符串總是「章節N」,你可以只處理它直接:

if (section.StartsWith("Section")) 
    Console.WriteLine(section.Insert(7, " ")); 
else 
    Console.WriteLine("Default Section"); 
+0

+1用於StartsWith/Insert。我總是在StackOverflow上學習一些東西:D – ray 2011-04-15 19:22:41

1

如果這是所有的數據驅動的,我建議你只是從數據庫連同該標識符字符串

表返回一些其他的顯示值AcceptedSections

Name = "Section1" 
DisplayName = "Section 1" 

然後,你可以只是返回DisplayName


如果不是你必須處理這就像你現在做的,或者你可以創建一個用於顯示的屬性的枚舉:

public enum AcceptedSections 
{ 
    [Description("Default Section")] 
    Default, 
    [Description("Section 1")] 
    Section1, 
    [Description("Section 2")] 
    Section2, 
    [Description("Section 3")] 
    Section3, 
    [Description("Section 4")] 
    Section4 
} 
// writing this made me kind woozy... what a terrible enum 

,這將使你喜歡寫東西這樣的:

foreach (AcceptedSections section in AcceptedSections.GetValues()) 
{ 
    Console.WriteLine(section.GetDescription()); 
} 

其中GetDescription()是返回一個簡單的方法是在枚舉

+0

我有一個投票,現在它已經走了......這就是生活 – hunter 2011-04-15 19:14:08

+0

你讓我直到編輯。使數據驅動的第一種方法爲顯示值的更改提供了最大的靈活性,而不必影響代碼(顯然,沒有初始更改以併入額外字段)。但是,再次添加一個枚舉會帶來與他試圖逃脫的相同挑戰:每次將一個部分添加到數據庫時更新代碼。 – 2011-04-15 19:14:45

+0

@Anthony是的,只是提出一個更容易管理的選項。管理一個枚舉比管理這個switch語句更好。但是,是的,數據驅動選項是首選。 – hunter 2011-04-15 19:15:52