下面是我现在的代码:
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 == ..。可以进一步简化吗?
发布于 2020-04-05 07:22:06
不幸的是,开关表达式目前只能匹配单个模式。有一个用于复合模式的特征请求,但现在没有更多。这是少数几个使用带有多个case标签的switch语句的领域之一,其结果可能比使用一个switch表达式更简单。(如果CC.F1等是可以在case标签中使用的常量,您可能需要考虑这个选项。)
在示例代码中,我可能只使用条件运算符,但我假设真正的开关表达式还有其他情况要考虑。
为了避免进行五次比较,您可以创建某种集合,只需使用var x when FCollection.Contains(x)作为您的保护模式。
发布于 2020-04-05 08:48:15
您还可以考虑完全放弃enum和switch,而改用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.";
...
}用自由手编写的示例,没有编译
如果添加了更多的属性,您可以根据自己的类型对每一张卡进行专门化。
在声明"enum“时,它需要更多的编码,但在使用它的任何地方都会简化--使代码更加可读性和可理解性。
https://stackoverflow.com/questions/61039247
复制相似问题