简体   繁体   English

C# 简化switch语句

[英]C# simplify switch statement

Can I somehow simplify this switch statement as both cases do same thing just with another function parameter?我可以以某种方式简化此 switch 语句,因为两种情况都只使用另一个 function 参数做同样的事情吗?

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 C# 参考

//Another clean approach without using Swtich case: //另一种不使用 Swtich 案例的干净方法:

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:另一种使用本地 function 来简化调用的方法:

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.该代码将始终对 null 进行额外测试,而直接开关不会这样做 - 所以这(非常边缘)效率较低。

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.像这样的简单本地函数很可能会被 JIT 编译器内联,所以应该没有开销。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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