开发者

Make this code snippet better

开发者 https://www.devze.com 2023-02-25 16:37 出处:网络
I have a program that has the following code: foreach (string section in DataAccessLayer.AcceptedSections)

I have a program that has the following code:

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;
    }                    
}

Is there anyway i can do what this code does without providing the section's string again within the case?开发者_开发技巧 The DataAccessLayer.AcceptedSections is dynamic and i don't want to have to add another section case to my code, rebuild and redeploy every time a new section comes on board. It's Friday and my mind is not working very well.

For Example: I don't want to add the following code when Section 4 gets added to the database:

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


If the string is always "SectionN", you could just handle it directly:

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


Have a Dictionary<string,Action<T>> that is keyed by section. This will completely replace the switch statement.

Invoke the corresponding action:

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


If this is all data-driven I suggest you just return some other display value from the database along with that identifier string

Table AcceptedSections

Name = "Section1"
DisplayName = "Section 1"

Then you can just just return the DisplayName


If it is not you'll have to handle this like you're doing now or you could create an enum with an attribute for display:

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

which will allow you to write something like this:

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

where GetDescription() is a simple method that returns that custom attribute on the enum

0

精彩评论

暂无评论...
验证码 换一张
取 消