繁体   English   中英

如何根据 C# 中的枚举值获得优势?

[英]How do I get an advantage depending on enum value in C#?

我正在尝试制作一个石头剪刀布游戏,用一个枚举来表示播放器或计算机播放的每个值:

public enum Choice
{
    Rock,
    Paper,
    Scissors
}

我想根据选择获得优势,但我不知道如何在 C# 中做到这一点,因为我习惯了 Java,它使枚举类可以修改以在其中创建函数。 基本上,我想获得当前有优势的选择。 (例如,Paper 优于 Rock,Scissors 优于 Paper,Rock 优于 Scissors)

我建议直接在您的Choice枚举下使用扩展方法,如下所示:

public enum Choice
{
  Rock,
  Paper,
  Scissors
}

public static class ChoiceExt
{
    public static Choice GetAdvantageByChoice(this Choice choice)
    {
        switch (choice)
        {
            case Choice.Rock:
                return Choice.Scissors;
            case Choice.Paper:
                return Choice.Rock;
            case Choice.Scissors:
                return Choice.Paper;
            default:
                throw new ArgumentException()
        }
    }
}

在扩展方法GetAdvantageByChoice ,第一个参数的类型将是扩展的类型,这就是为什么我们必须在它前面添加this修饰符。

另外,正如 Jeroen Mostert 所说,您可以更简洁地编写switch

public static Choice GetAdvantageByChoice(this Choice choice) =>
  choice switch
  {
      Choice.Paper => Choice.Rock,
      Choice.Rock => Choice.Scissors,
      Choice.Scissors => Choice.Paper,
      _ => throw new ArgumentException()
  };

一个更简单优雅的解决方案,使用C#8 switch表达式

var choice = Choice.Paper; //for example
var result = choice switch
{
    Choice.Paper => Choice.Rock,
    Choice.Rock => Choice.Scissors,
    Choice.Scissors => Choice.Paper,
    _ => throw new ArgumentOutOfRangeException()
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM