我如何安全地投了System.Object的一个`bool`在C#中? [英] How do I safely cast a System.Object to a `bool` in C#?
问题描述
我提取一个(非通用,hetrogeneous)集合布尔
值。
I am extracting a bool
value from a (non-generic, hetrogeneous) collection.
在为
运营商可能只引用类型使用,所以这是不可能做到的使用为
来尝试一个安全,强制转换为布尔
:
The as
operator may only be used with reference types, so it is not possible to do use as
to try a safe-cast to bool
:
// This does not work: "The as operator must be used with a reference type ('bool' is a value type)"
object rawValue = map.GetValue(key);
bool value = rawValue as bool;
有没有类似的事情可以做,所以安全对象转换值类型没有的可能性 InvalidCastException的
如果,无论出于何种原因,该值不是一个布尔?
Is there something similar that can be done so safely cast an object to a value type without possibility of an InvalidCastException
if, for whatever reason, the value is not a boolean?
推荐答案
有两个选项...略有令人惊讶的表现:
There are two options... with slightly surprising performance:
-
冗余校验:
Redundant checking:
if (rawValue is bool)
{
bool x = (bool) rawValue;
...
}
使用可空类型:
Using a nullable type:
bool? x = rawValue as bool?;
if (x != null)
{
... // use x.Value
}
令人惊讶的是,在<一个href="http://stackoverflow.com/questions/1583050/performance-surprise-with-as-and-nullable-types">performance第二形式的比第一的差很多。
The surprising part is that the performance of the second form is much worse than the first.
这篇关于我如何安全地投了System.Object的一个`bool`在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!