简体   繁体   中英

Does C# have any equivalent to Elixir's `cond`?

In Elixir, if I want to check multiple boolean conditions, rather than some ugly mess of if/else logic, I can elegantly do this:

guess = 46
number_of_guesses = 3
cond do
   number_of_guesses > 5 -> 
      IO.puts "Too many guesses!  You lose."

   guess == 46 -> 
      IO.puts "You guessed 46!"

   guess == 42 -> 
      IO.puts "You guessed 42!"

   true        -> 
      IO.puts "I give up."
end

The above program generates the following result −

You guessed 46!

(Example derived from Tutorialspoint , but further contrived to demonstrate not every expression must contain the same variable.)

Does C# have anything similar or would I need to use if/else?

If you are matching against a value in almost all of the cases, you can still use a switch expression , with case guards:

int guess = 46;
int numberOfGuesses = 3;
Console.WriteLine(
    guess switch {
        _ when numberOfGuesses > 5 => "Too many guesses!  You lose.",
        46 => "You guessed 46!",
        42 => "You guessed 42!",
        _ => "I give up."
    }
);

Notice that in the first arm, I matched anything (the underscore _ pattern) but only "when numberOfGuesses > 5". Or in this case you can even do fancier pattern matching:

Console.WriteLine(
    (guess, numberOfGuesses) switch
    {
        (_, > 5) => "Too many guesses!  You lose.",
        (46, _) => "You guessed 46!",
        (42, _) => "You guessed 42!",
        _ => "I give up."
    }
);

But of course, this is not possible in every situation.

If all the arms are unrelated conditions, using this sort of _ when ... construct feels a bit abusive, so alternatively, you can use a chain of ternary operators :

var x = 
    condition1 ?
        someValue1 :
    condition2 ?
        someValue2 :
    condition3 ?
        someValue3 :
    valueWhenNoConditionsAreTrue;

Though I feel even this can be a bit astonishing on first sight.

If you want to execute statements in those branches, rather than expressions, then you should just use a plain-old if-else-if structure.

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