如何:从 bool? 安全地强制转换为 bool(C# 编程指南)
2013-10-22 17:28
351 查看
bool? 可以为 null 的类型可以包含三个不同的值:true、false 和 null。
若要在条件语句中使用 bool?,请首先检查其 HasValue 属性以确保其值不是 null,然后将它强制转换为 bool。
如:
若要在条件语句中使用 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. }
相关文章推荐
- 如何:从 bool? 安全地强制转换为 bool(C# 编程指南)
- 如何:将字节数组转换为 基本类型(C# 编程指南)
- 如何:在十六进制字符串与数值类型之间转换(C# 编程指南)
- 如何:定义抽象属性(C# 编程指南)
- 如何:创建和终止线程(C# 编程指南)
- 编程技巧:C#中的Cast By Example(如何将弱类型的匿名类型参数转换为强类型)
- 如何:使用 Split 方法分析字符串(C# 编程指南)
- 如何:通过使用 Visual C# 2010 功能访问 Office 互操作对象(C# 编程指南)
- 如何:合并委托(多路广播委托)(C# 编程指南)
- 如何:使用 Split 方法分析字符串(C# 编程指南)
- 如何:声明、实例化和使用委托(C# 编程指南)GOOD
- [C#] as 和 is 运算符以及安全的类型强制转换
- 从 bool? 安全地强制转换为 bool
- 如何:创建和终止线程(C# 编程指南)
- 如何:使用线程池(C# 编程指南《msdn线程池》
- 如何:声明、实例化和使用委托(C# 编程指南)
- 如何:使用 foreach 访问集合类(C# 编程指南)
- 如何:对制造者线程和使用者线程进行同步(C# 编程指南)
- 在十六进制字符串与数值类型之间转换 C# 编程指南
- 如何:订阅和取消订阅事件(C# 编程指南)