如何将带有或条件的if语句转换为三元语句?
本文关键字:语句 转换 三元 if 条件 | 更新日期: 2023-09-27 17:52:59
我有这样的代码
if (ScalarReturned is DBNull)
{
xCount = 0;
}
else
{
xCount = (Int32)ScalarReturned;
}
工作得很好,但只是想转换为内联IF——我在下面尝试,但得到多个编译错误。有人能帮忙吗?
if (ScalarReturned is DBNull) ? xCount = 0 : xCount = (Int32)ScalarReturned;
这样做:
xCount = ScalarReturned is DBNull || ScalarReturned == null ? 0 :
(Int32)ScalarReturned;
工作原理:
三元操作符的作用有点像函数。这里唯一的问题是,您不需要return
关键字。
用简单的英语说:
如果满足第一个条件ScalarReturned is DBNull || ScalarReturned
,则赋0给xCount,否则赋:
之后的值
试试这个:
xCount = ScalarReturned is DBNull || ScalarReturned == null ? 0 : (Int32)ScalarReturned;
您没有正确使用三元运算符
试试这个:
xCount = (ScalarReturned is DBNull || ScalarReturned == null) ? 0 :
(Int32)ScalarReturned;
xCount = (ScalarReturned is DBNull || ScalarReturned == null) ? 0 : (Int32)ScalarReturned;(
三元运算符的操作如下:
condition ? true result : false result
xCount = (Int32)((ScalarReturned is DBNull || ScalarReturned == null) ? 0 : ScalarReturned);
您可以在ScalarReturned == DBNull.Value
上使用?
运算符:
int xCount = ScalarReturned == DBNull.Value ? 0 : (Int32)ScalarReturned;