我正在从一个(非泛型的、异构的)集合中提取一个 bool
值。
as
操作符只能用于引用类型,因此不可能使用 as
尝试安全转换到 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
?