简体   繁体   中英

C# simplify switch statement

Can I somehow simplify this switch statement as both cases do same thing just with another function parameter?

switch (data.Subscriber.Protocol)
{
    case "email json":
        builder.Attachments.Add("Očitanje.json", CraftAttachment(data));
        break;
    case "email text":
        builder.Attachments.Add("Očitanje.txt", CraftAttachment(data));
        break;
    default:
        break;
}

How about something like this:

string attachmentName = data.Subscriber.Protocol switch
{
    "email json" => "Očitanje.json",
    "email text" => "Očitanje.txt",
    _ => null
};

if (attachmentName is not null)
{
    builder.Attachments.Add(attachmentName, CraftAttachment(data));
}

Switch expression | C# reference

//Another clean approach without using Swtich case:

var ProtocolAndFileMappings = new Dictionary<string, string>()
    {
       {"email json","Očitanje.json"},
       {"email text","Očitanje.json"},
       {"email png","Očitanje.png"},
       {"email Jpeg","Očitanje.Jpeg"}
     };

 builder.Attachments.Add(ProtocolAndFileMappings[data.Subscriber.Protocol], CraftAttachment(data));

Another approach using a local function to simplify the call:

void add(string s) => if (s != null) builder.Attachments.Add(s, CraftAttachment(data));

add( data.Subscriber.Protocol switch
{
    "email json" => "Očitanje.json",
    "email text" => "Očitanje.txt",
    _ => null
});

(Although I think that some folks would criticize that as "too cute...)

NOTE: This solution (like the other solutions) suffers from a drawback.

The code will always make an additional test against null, which the straightforward switch doesn't do - so this is (very marginally) less efficient.

I personally would do it like this (which avoids the drawback):

void add(string s) => builder.Attachments.Add(s, CraftAttachment(data));

switch (data.Subscriber.Protocol)
{
    case "email json": add("Očitanje.json"); break;
    case "email text": add("Očitanje.txt")   break;
    default:           /* Do nothing */      break;
}    

Simple local functions like that are very likely to be inlined by the JIT compiler, so there should be no overhead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM