Ternary with boolean condition in c#

…衆ロ難τιáo~ 提交于 2019-12-02 14:59:41

问题


If I am to write this piece of code, it works fine with the normal 'if-else' layout.

if(isOn)
{
    i = 10;
}
else
{
    i = 20;
}

Although I am unsure how to convert this using the ternary operator

        isOn = true ? i = 1 : i = 0;

Error: Type of conditional expression cannot be determined because there is no implicitly conversion between 'void' and 'void'.

EDIT: Answer = i = isOn ? 10 : 20;

Is it possible to do this with methods?

if(isOn)
{
    foo();
}
else
{
    bar();
}

回答1:


Please try the following. BTW, it only works for value assignments not method calls.

i = isOn ? 10 : 20;

Reference:

  • ?: Operator (C# Reference)



回答2:


You may simply try this:

i = isOn? 10:20

The MSDN says:

The condition must evaluate to true or false. If condition is true, first_expression is evaluated and becomes the result. If condition is false, second_expression is evaluated and becomes the result. Only one of the two expressions is evaluated.

EDIT:-

If you want to invoke void methods in a conditional operator, you can use delegates else it is not possible to use ternary operators for methods.

And if your methods are returning something then try like this:

i = isOn ? foo() : bar();    //assuming both methods return int



回答3:


You're on the right track but a little off. i = isOn ? 10 : 20;

Here 10 will be assigned to i if isOn == true and 20 will be assigned to i if isOn == false




回答4:


try the following

i = isOn ? 10 :20



回答5:


Try the following:

i = isOn ? 10 : 20



回答6:


Here's an explanation that might help. The statement you're looking for is:

i = isOn ? 10 : 20;

And here's what that means:

(result) = (test) ? (value if test is true) : (value if test is false);



回答7:


You need:

i = true ? 10 : 20;

where true is your condition.



来源:https://stackoverflow.com/questions/25572062/ternary-with-boolean-condition-in-c-sharp

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