如何:从 bool? 安全地强制转换为 bool?C# 编程指南

bool? 可以为 null 的类型可以包含三个不同的值:true、false 和 null。

若要在条件语句中使用 bool?,请首先检查其 HasValue 属性以确保其值不是 null,然后将它强制转换为 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.
            }