2011-04-15 61 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