如何将带有或条件的if语句转换为三元语句?

时间:2014-03-25 15:04:54

标签: c# if-statement

我有这段代码

if (ScalarReturned is DBNull)
{
    xCount = 0;
}
else
{
    xCount = (Int32)ScalarReturned;
}

哪个很好但只是想转换为内联IF - 我试过下面但是得到了多个编译错误。有人可以协助吗?

if (ScalarReturned is DBNull) ? xCount = 0 : xCount = (Int32)ScalarReturned;

6 个答案:

答案 0 :(得分:4)

这样做:

xCount = ScalarReturned is DBNull || ScalarReturned == null ?  0 :
                                                          (Int32)ScalarReturned;

工作原理:

三元运算符有点像函数。这里唯一的问题是,您不需要return关键字。

用简单的英语:

如果满足第一个条件ScalarReturned is DBNull || ScalarReturned,则将0分配给xCount,否则分配:之后的内容

答案 1 :(得分:1)

试试这个:

xCount = ScalarReturned is DBNull || ScalarReturned == null ? 0 : (Int32)ScalarReturned;

答案 2 :(得分:1)

您没有正确使用三元运算符

试试这个:

xCount  = (ScalarReturned is DBNull || ScalarReturned == null) ?  0 : 
                                                     (Int32)ScalarReturned;

答案 3 :(得分:1)

xCount = (ScalarReturned is DBNull || ScalarReturned == null) ? 0 : (Int32)ScalarReturned;(

答案 4 :(得分:1)

三元运算符的工作原理如下:

condition ? true result : false result

xCount = (Int32)((ScalarReturned is DBNull || ScalarReturned == null) ? 0 : ScalarReturned);

答案 5 :(得分:0)

您可以使用ScalarReturned == DBNull.Value上的? operator

int xCount = ScalarReturned == DBNull.Value ? 0 : (Int32)ScalarReturned;