简体   繁体   中英

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

I'm trying to make a Rock, Paper, Scissors game, with an enum to represent each value that the Player or the Computer plays :

public enum Choice
{
    Rock,
    Paper,
    Scissors
}

I want to get an advantage depending on the Choice, but I don't know how to do it in C#, since I'm used to Java which makes enum classes modifiable for creating functions within them. Basically, I want to get the Choice that the current one has an advantage on. (For example, Paper has an advantage over Rock, Scissors has an advantage over Paper and Rock has an advantage over Scissors)

I recommend to use an extension method directly under your Choice enum like this :

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

In GetAdvantageByChoice , which is the extension method, the type of the first parameter will be the type that is extended, that's why we have to add the this modifier in front of it.

Also, as Jeroen Mostert said, you can write the switch more concisely :

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

A more simple and elegant solution, using the C#8 switch expression

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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