C#中具有布尔条件的三元 [英] Ternary with boolean condition in c#

查看:60
本文介绍了C#中具有布尔条件的三元的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我要编写这段代码,则可以正常使用 if-else布局。

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'.

编辑:
答案= i = isOn吗? 10:20;

是否可以用方法做到这一点?

Is it possible to do this with methods?

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


推荐答案

请尝试以下操作。顺便说一句,它仅适用于值分配而不适用于方法调用。

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

i = isOn ? 10 : 20;






参考:

  • ?: Operator (C# Reference)

这篇关于C#中具有布尔条件的三元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆