我正在尝试转换 object
到 bool
输入并要转换 bool
和 Nullable<bool>
类型。我还想确保在可能的情况下进行适当的转换。所以我有以下代码:
if (value is bool)
{
boolValue = (bool) value;
}
else if (value is bool? && ((bool?)value).HasValue)
{
boolValue = ((bool?) value).Value;
}
else
{
throw new ArgumentException("Value must be a boolean type");
}
ReSharper 2016 通知我 value is bool?
在这堆 if 语句中将始终评估为 false。这是为什么?这意味着 Nullable<bool>
不继承自 object
(不可能)或者那个value is bool
将捕获 bool?
.
ReSharper 2016 也有可能存在错误;我看到 System.Windows.Controls.BooleanToVisibilityConverter.Convert
的执行几乎相同。我怀疑 WPF 核心会不会有这样的错误,让我相信这是 ReSharper 的问题。
最佳答案
当值类型存储为 object
时它是 boxed . Nullable<T>
的拳法|得到 special treatment :
Objects based on nullable types are only boxed if the object is non-null. If HasValue is false, the object reference is assigned to null instead of boxing ... Boxing a non-null nullable value type boxes the value type itself, not the System.Nullable that wraps the value type.
并且,根据 documentation for is
:
An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.
因此,使用这两个你可以推断(参见 fiddle)在 null 情况下:
bool? x = null;
object obj = x; // assigns obj = null
obj is bool? // false, obj is null
obj is bool // false, obj is null
在非空情况下:
bool? x = true;
object obj = x; // obj is boxed bool (true)
obj is bool? // true, obj unboxes to bool?
obj is bool // true, obj unboxes to bool
所以 ReSharper 是正确的:您的第一个分支将评估为 true
如果value
是true
或 false
(对象是从 bool
还是 bool?
分配的不相关甚至不知道)。第二个分支永远是 false
在这种情况下。
关于C# is operator with nullable types always false 根据 ReSharper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37496148/