从 bool? 安全地强制转换为 bool ??应用

bool? 可以为 null 的类型可以包含三个不同的值:truefalse 和 null。因此,bool? 类型不能用于条件语句,如 iffor 或 while。例如,此代码无法编译,并将报告编译器错误 CS0266

 
 
bool? b = null;
if (b) // Error CS0266.
{
}

这是不允许的,因为 null 在条件上下文中的含义并不清楚。若要在条件语句中使用 bool?,请首先检查其 HasValue 属性以确保其值不是 null,然后将它强制转换为 bool。有关更多信息,请参见 bool。如果对使用 null 值的 bool? 执行强制转换,则在条件测试中将引发InvalidOperationException。下面的示例演示了一种从 bool? 安全地强制转换为 bool 的方法:

示例
 
 
 
            bool? test = null;
             ...// Other code that may or may not
                // give a value to test.
            if(!test.HasValue) //check for a value
            {
                // Assume that IsInitialized
                // returns either true or false.
                test = IsInitialized();
            }
            if((bool)test) //now this cast is safe
            {
               // Do something.
            }


public bool? c = null;
public bool T()
{

return c ?? false;

} 解释

如果 ?? 运算符的左操作数非 null,该运算符将返回左操作数,否则返回右操作数。

 p ?? false
posted @ 2013-09-09 15:34  zhengrunqiang  阅读(800)  评论(0编辑  收藏  举报