您的位置:首页 > 编程语言 > C#

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

2013-10-22 17:28 351 查看
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.
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: