C#在条件语句中可为空 [英] C# Nullable in conditional statement
本文介绍了C#在条件语句中可为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么我们需要在第二条语句中进行显式转换?
Why do we need explicit cast in second statement?
bool? a = null;
bool b = false;
bool c = true;
1。)
if(b || c )
a = b;
else
a = null;
2。) a =(b || c )?(Nullable< bool>)b:null;
推荐答案
条件运算符是一个表达式,因此它需要一个返回类型-同样,两种情况都必须具有相同的返回类型。在您的情况下,无法自动确定返回类型,因此需要强制转换。
The conditional operator is an expression, thus it needs a return type - also both cases have to have the same return type. In your case, there is no way of determining the return type automatically, thus you need to cast.
这篇关于C#在条件语句中可为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文