使此代码段更好

| 我有一个包含以下代码的程序:
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;
    
已邀请:
有一个以
section
键控的
Dictionary<string,Action<T>>
。这将完全替换switch语句。 调用相应的操作:
foreach (string section in DataAccessLayer.AcceptedSections)
{
    myActionsDictionary[section]();
}
    
如果字符串始终为\“ SectionN \”,则可以直接处理它:
if (section.StartsWith(\"Section\"))
    Console.WriteLine(section.Insert(7, \" \"));
else
    Console.WriteLine(\"Default Section\");
    
如果这全部是数据驱动的,那么我建议您从数据库中返回其他一些显示值以及该标识符字符串 表的接受部分
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());
}
其中“ 10”是一个简单的方法,可在枚举上返回该自定义属性     

要回复问题请先登录注册