我有这样的代码,其中开关的每个部分都将一个值返回给ModeMessage2。是否可以使用新的C# switch表达式(或任何其他代码优化)来优化switch的工作方式?
switch (Settings.Mode)
{
case MO.Learn:
ModeMessage2 =
"Use this mode when you are first learning the phrases and their meanings.";
if (Settings.Cc == CC.H)
{
Settings.Cc = CC.JLPT5;
App.cardSetWithWordCount = null;
App.DB.RemoveSelected();
}
break;
case MO.Practice:
ModeMessage2 =
"Use this mode to help you memorize the phrases and their meanings.";
if (Settings.Cc == CC.H)
{
Settings.Cc = CC.JLPT5;
App.cardSetWithWordCount = null;
App.DB.RemoveSelected();
}
break;
case MO.Quiz:
if (Settings.Cc == CC.H)
{
Settings.Cc = CC.JLPT5;
App.cardSetWithWordCount = null;
App.DB.RemoveSelected();
}
App.DB.UpdSet(SET.Adp, false);
ModeMessage2 =
"Use this mode to run a self marked test.";
break;
}发布于 2019-11-22 17:12:48
您的代码类似于下面的代码,尽管如果设置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);发布于 2019-11-22 17:07:40
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);
}发布于 2019-11-22 17:13:41
你应该用字典来做这个--
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]);这将比任何开关语句快得多,而且更容易维护。
如果这有意义的话,也可以使用数组。
注意下面的注释:我做了以下假设,在某些情况下可能是错误的,但在一般情况下则不然。1)代码的编写方式是,“分配”只在代码的生存期内发生一次--在这种情况下,如果使用映射不止一次,就可以节省费用,这样在N次之后分配成本就会达到0。2)我们不知道键的类型,假设它是字符串的注释正在做出一个可能不正确的假设。即使如此,对字符串的任何“快速”比较都使用哈希,这与字典用于获得速度的方法相同。众所周知,在编程中你能做的最慢的事情就是一个分支。字典(或数组映射)允许您没有任何分支,只需要计算到内存位置。
https://stackoverflow.com/questions/58998500
复制相似问题