【问题标题】:Is there a way I can further simplify a C# switch expression with multiple values in one case? [duplicate]有没有一种方法可以在一种情况下进一步简化具有多个值的 C# switch 表达式? [复制]
【发布时间】:2020-04-05 07:16:40
【问题描述】:

这是我现在拥有的代码:

        return cardChoice switch
        {
            var x when
                x == CC.F1 ||
                x == CC.F2 ||
                x == CC.F3 ||
                x == CC.F4 ||
                x == CC.F5 => $"There are 0 cards in this collection.Add cards by tapping > of any card set then choose {cardChoice}.",
                CC.H       => "There are 0 cards in this collection. Add cards by tapping > of any card set then choose Hide.",
            _ => throw new InvalidEnumArgumentException("Unhandled value: " + cardChoice.ToString()),
        };

有没有办法进一步简化 x == .. 的检查?

【问题讨论】:

  • F1F2等到底是什么,为什么它们不存储为数组或列表?

标签: c#


【解决方案1】:

不幸的是,switch 表达式目前只能匹配一个模式。复合模式有一个feature request,但现在仅此而已。这是使用带有多个 case 标签的 switch 语句最终比使用 switch 表达式更简单的少数领域之一。 (如果CC.F1 等是可用于案例标签的常量,您可能需要考虑该选项。)

在您的示例代码中,我可能只使用条件运算符,但我假设您的真实 switch 表达式还有其他情况需要考虑。

就避免进行五次比较而言,您可以创建某种集合并使用 var x when FCollection.Contains(x) 作为您的保护模式。

【讨论】:

    【解决方案2】:

    您也可以考虑完全放弃enumswitch,而改用Enumeration class

    这样你的代码最终会变成:

    public CardType : Enumeration
    {
        public CardType( int id, string name, bool chooseCard )
          : base(id,name)
        {
          ChooseCard = chooseCard;
        }
    
        public static readonly Unknown = new CardType(-1,"unknown", false);
        public static readonly F1 = new CardType(1,"F1", true);
        public static readonly F2 = new CardType(2,"F2", true);
        public static readonly F3 = new CardType(3,"F3", true);
        public static readonly F4 = new CardType(4,"F4", true);
        public static readonly F5 = new CardType(5,"F5", true);
        public static readonly H = new CardType(10,"H", false);
    
        public bool ChooseCard { get; }
        public bool ChooseHide => ChooseCard == false;
        public bool IsUnknown => Id == Unknown.Id;
    }
    
    TestChoice( CardType cardChoice ) {
      if( cardChoice.IsUnknown )
         throw new InvalidEnumArgumentException("Unhandled value: " + cardChoice.ToString());  
      if( cardChoice.ChooseCard )
        return $"There are 0 cards in this collection.Add cards by tapping > of any card set then choose {cardChoice}.";
      if( cardChoice.ChooseHide )
        return "There are 0 cards in this collection. Add cards by tapping > of any card set then choose Hide.";
     ...
    }
    

    例子是徒手写的,没有编译

    如果添加了更多属性,您可以根据自己的类型专门化每张卡。

    在声明“枚举”时需要更多的编码,但简化了它的使用位置 - 使代码更具可读性和可理解性。

    在此处阅读更多信息:https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/enumeration-classes-over-enum-types

    【讨论】:

      猜你喜欢
      • 2011-09-30
      • 1970-01-01
      • 2012-07-24
      • 2010-10-07
      • 1970-01-01
      • 2011-01-03
      • 2013-03-08
      • 2021-03-15
      • 2016-11-01
      相关资源
      最近更新 更多