Calling functions in C# ternary operator [duplicate]

让人想犯罪 __ 提交于 2019-11-28 09:22:21

问题


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.



来源:https://stackoverflow.com/questions/38450938/calling-functions-in-c-sharp-ternary-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!