【问题标题】:How do I declare parameters returned from a C# 8 switch expression?如何声明从 C# 8 switch 表达式返回的参数?
【发布时间】:2020-03-19 09:07:50
【问题描述】:

我在看这段代码:

public enum MO
{
    Learn, Practice, Quiz
}

public enum CC
{ 
    H
}

public class SomeSettings
{
    public MO Mode { get; set; }
    public CC Cc { get; set; }
}

static void Main(string[] args)
{
    var Settings = new SomeSettings() { Cc = CC.H, Mode = MO.Practice };

    var (msg,isCC,upd) = Settings.Mode switch {
        case MO.Learn => ("Use this mode when you are first learning the phrases and their meanings.",
                          Settings.Cc == CC.H,
                          false),
        case MO.Practice => ("Use this mode to help you memorize the phrases and their meanings.",
                          Settings.Cc == CC.H,
                          false),
        case MO.Quiz => ("Use this mode to run a self marked test.",
                          Settings.Cc == CC.H,
                          true);
        _ => default;
    }
}

不幸的是,msgisCCupd 似乎没有正确声明,它给出了一条消息:

无法推断隐式类型解构变量的类型 'msg' 和 isCC 和 upd 一样。

你能帮我解释一下如何声明这些吗?

【问题讨论】:

  • 有在线的 C# 8 编译器来试试这个吗?
  • 您能在minimal reproducible example 中复制此内容吗?这样可以更轻松地为您提供帮助,而不是每个潜在的回答者都必须做同样的工作来重现它。
  • @PavelAnikhouski 问题的重点是 OP 出现编译错误。
  • 是否有任何关于 default 关键字作用的文档? “新功能”页面没有说明任何内容,我想知道这是否是问题所在。
  • 这个问题是答案here的结果吗?

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


【解决方案1】:

case 标签是带有 switch 表达式的 not used,中间有一个;,后面没有;

var (msg, isCC, upd) = Settings.Mode switch {
    MO.Learn => ("Use this mode when you are first learning the phrases and their meanings.",
                        Settings.Cc == CC.H,
                        false),
    MO.Practice => ("Use this mode to help you memorize the phrases and their meanings.",
                        Settings.Cc == CC.H,
                        false),
    MO.Quiz => ("Use this mode to run a self marked test.",
                        Settings.Cc == CC.H,
                        true),
    _ => default
};

【讨论】:

    【解决方案2】:

    我写的是没有检查的,但你可以试试这样的:

    (string msg, bool isCC, bool upd) result = Settings.Mode switch ... <rest of your code>
    

    然后像这样使用它:

    result.msg
    

    【讨论】:

      猜你喜欢
      • 2020-01-10
      • 1970-01-01
      • 1970-01-01
      • 2020-03-18
      • 2020-07-14
      • 2020-03-14
      • 2020-05-10
      • 2023-02-09
      • 2019-08-01
      相关资源
      最近更新 更多