简体   繁体   English

C# 有什么等同于 Elixir 的 `cond` 吗?

[英]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:在 Elixir 中,如果我想检查多个布尔条件,而不是一些丑陋的 if/else 逻辑,我可以优雅地这样做:

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!你猜对了 46!

(Example derived from Tutorialspoint , but further contrived to demonstrate not every expression must contain the same variable.) (从Tutorialspoint派生的 示例,但进一步人为地证明并非每个表达式都必须包含相同的变量。)

Does C# have anything similar or would I need to use if/else? C# 是否有类似的东西,或者我需要使用 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:如果您在几乎所有情况下都匹配某个值,您仍然可以使用带有 case 保护的switch 表达式

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".请注意,在第一个分支中,我匹配了任何内容(下划线_模式),但仅匹配“当 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 :如果所有的分支都是不相关的条件,使用这种_ when ...构造感觉有点滥用,所以或者,您可以使用三元运算符

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.如果你想在这些分支中执行语句,而不是表达式,那么你应该只使用一个普通的 if-else-if 结构。

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

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