有没有一种方法可以使用C#8开关表达式来返回字符串值?

时间:2019-11-22 16:47:00

标签: c# switch-statement c#-8.0 switch-expression

我有这段代码,其中开关的每个部分都向QDialog.Rejected返回一个值。是否可以使用新的C#ModeMessage2表达式(或任何其他代码优化)来优化此switch的工作方式?

switch

3 个答案:

答案 0 :(得分:2)

您的代码与以下代码相似,但是如果设置ModeMessage2或其他属性有副作用,那么事情发生的顺序可能很重要,在这种情况下,这在技术上并不是100%等效的。

IList<MO> specialModes = new[] { MO.Learn, MO.Practice, MO.Quiz };

if (specialModes.Contains(Settings.Mode) && Settings.Cc == CC.H) {
   Settings.Cc = CC.JLPT5;
   App.cardSetWithWordCount = null;
   App.DB.RemoveSelected();
}

ModeMessage2 = Settings.Mode switch {
   MO.Learn => "Use this mode when you are first learning the phrases and their meanings.",
   MO.Practice => "Use this mode to help you memorize the phrases and their meanings.",
   MO.Quiz => "Use this mode to run a self marked test.",
   _ => "Unknown mode value" // or throw
};

if (Settings.Mode == MO.Quiz)
   App.DB.UpdSet(SET.Adp, false);

答案 1 :(得分:1)

var modeMessage2 = Settings.Mode switch
{
    MO.Learn => "Use this mode when you are first learning the phrases and their meanings.",
    MO.Practice => "Use this mode to help you memorize the phrases and their meanings.",
    MO.Quiz => "Use this mode to run a self marked test."
}

if (Settings.Cc == CC.H)
{
    Settings.Cc = CC.JLPT5;
    App.cardSetWithWordCount = null;
    App.DB.RemoveSelected();
}

if (Settings.Mode == MO.Quiz) {
    App.DB.UpdSet(SET.Adp, false);
}

答案 2 :(得分:1)

您应该使用字典来做到这一点-

 Dictionary<TypeOf(Settings.Mode), string> map = new Dictionary<TypeOf(Settings.Mode), string>();

 map.Add(MO.Learn,"Use this mode when you are first learning the phrases and their meanings.");
 map.Add(MO.Practice,"Use this mode to help you memorize the phrases and their meanings.");
 map.Add(MO.Quiz,"Use this mode to run a self marked test.");


 ModeMessage2 = map[Settings.mode]);

这将比任何switch语句都快得多,并且更易于维护。

如果有必要,您也可以使用数组。


以下评论者的注意事项:我正在做以下假设,在某些情况下可能是错误的,但在一般情况下不会如此。 1)以这样的方式编写代码:在代码的整个生命周期中,“分配”仅发生一次-在这种情况下,如果多次使用地图,您将获得节余,因此在N次分配之后到0。2)我们不知道键的类型,假设它是字符串的注释正在作出可能不正确的假设。即使如此,字符串的任何“快速”比较都使用哈希,这与字典用来提高速度的方法相同。 3)众所周知,编程中最慢的事情是分支。字典(或数组映射)允许您不具有任何分支,而只是计算内存位置。