更新:2007 年 11 月
bool? 可以为 null 的类型可以包含三个不同的值:true、false 和 null。因此,bool? 类型不能用于条件语句,如 if、for 或 while。例如,此代码无法编译,并将报告
bool? b = null;
if (b) // Error CS0266.
{
} | |
这是不允许的,因为 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.
} | |