Calling functions in C# ternary operator [duplicat

2019-02-26 19:58发布

问题:

This question already has an answer here:

  • C# Conditional Operator Not a Statement? 9 answers

Why is this code not valid? Pretty sure it's legit in C /C++

Pseudocode:

String s = Console.ReadLine();
int x = 0;
Int32.TryParse(s, out x) ? Console.WriteLine("Foo") :  Console.WriteLine("bar");

回答1:

The ternary operator is used to return values and those values must be assigned.

If you want to invoke void methods in a ternary operator, you can use delegates like this:

String s = Console.ReadLine();
int x = 0;
(Int32.TryParse(s, out x) ? new Action(() => Console.WriteLine("Foo")) : () => Console.WriteLine("bar"))();


回答2:

console.writeline return void.. The conditional operator (?:) returns one of two values depending on the value of a Boolean expression

MSDN



回答3:

As discussed here, in C#, not every expression can be used as a statement.