使这段代码更好

时间:2011-04-15 19:03:40

标签: c# .net design-patterns

我的程序包含以下代码:

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;

3 个答案:

答案 0 :(得分:5)

如果字符串始终是“SectionN”,您可以直接处理它:

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

答案 1 :(得分:3)

拥有由Dictionary<string,Action<T>>键入的section。这将完全取代switch语句。

调用相应的操作:

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

答案 2 :(得分: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()是一个简单的方法,它在枚举

上返回该自定义属性
相关问题