gpt4 book ai didi

c# - 有没有一种方法可以让 switch 使用 C# 8 switch 表达式返回字符串值?

转载 作者:太空宇宙 更新时间:2023-11-03 20:47:50 24 4
gpt4 key购买 nike

我有这段代码,其中开关的每个部分都向 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;
}

最佳答案

您的代码类似于以下内容,但如果设置 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);

关于c# - 有没有一种方法可以让 switch 使用 C# 8 switch 表达式返回字符串值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58998500/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com