【问题标题】:How do I get an advantage depending on enum value in C#?如何根据 C# 中的枚举值获得优势?
【发布时间】:2020-05-09 01:52:48
【问题描述】:

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

public enum Choice
{
    Rock,
    Paper,
    Scissors
}

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

【问题讨论】:

  • 提示:代码不一定要在枚举中才能实现。

标签: c# enums


【解决方案1】:

我建议在您的Choice 枚举下直接使用extension method,如下所示:

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()
  };

【讨论】:

  • 哦,我不知道扩展方法,谢谢你的回答。
  • 这个特殊的 switch 可以用 C# 8 的 switch expressions 和表达式主体更简洁地编写。我提到这一点只是因为它是一个特别好的案例。
【解决方案2】:

更简单优雅的解决方案,使用 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()
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多