C# is operator with nullable types always false 根据 ReSharper

标签 c# type-conversion resharper nullable resharper-2016

我正在尝试转换 objectbool输入并要转换 boolNullable<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如果valuetruefalse (对象是从 bool 还是 bool? 分配的不相关甚至不知道)。第二个分支永远是 false在这种情况下。

关于C# is operator with nullable types always false 根据 ReSharper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37496148/

相关文章:

c# - 如何在 LINQ 查询中获得与 ISNULL 相同的功能

c++ - `int*[1]` 和 `int(*)[1]` 有什么区别?

c# - 如何在 Resharper 4.5 中使用 bdd 命名风格?

c# - 使用 Span<T> 不进行任何分配的子字符串

c# - 我如何遍历 XPathNodeIterator 并随机化它的 child ?

initialization - 用 Go 中的类型声明替换包装结构

c# - ReSharper 单元测试运行程序对外部类给出不确定性

c# - ReSharper:覆盖默认命名空间以防止 "Namespace does not correspond to file location"

c# - LINQ 中的隐式转换错误

c++将类的实例转换为另一个