Calling functions in C# ternary operator [duplicat

2019-02-26 20:15发布

This question already has an answer here:

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");

3条回答
老娘就宠你
2楼-- · 2019-02-26 20:16

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

查看更多
Bombasti
3楼-- · 2019-02-26 20:29

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

MSDN

查看更多
SAY GOODBYE
4楼-- · 2019-02-26 20:30

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"))();
查看更多
登录 后发表回答