从 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()
{this

return c ?? false;spa

} 解释code

若是 ?? 运算符的左操做数非 null,该运算符将返回左操做数,不然返回右操做数。
 p ?? false
相关文章
相关标签/搜索