给定的表达式始终是提供的类型

The given expression is always of the provided type

为什么在值类型上使用 is 时 Visual Studio 会发出警告,而在引用类型上则不会?第 1 行和第 2 行发出警告,而第 3 行和第 4 行则没有。

if (5 is object)
if (new Point() is object)

if ("12345" is object)
if (new StringBuilder() is object)

因为微软没有实现。但它是例如由 JetBrains ReSharper.

实施

Visual Studio 显示 2 个编译器警告:

ReSharper 显示 4 个警告:

is 运算符不能重载。

Note that the is operator only considers reference conversions, boxing conversions, and unboxing conversions. Other conversions, such as user-defined conversions, are not considered.

来源:MSDN

这是一种启发式算法,根据定义,启发式算法是不完整的。

可在此处找到此启发式的源代码:Roslyn Source: Binder.GetIsOperatorConstantResult。该代码包含以下引用:

// The result of "x is T" can be statically determined to be true if x is an expression 
// of non-nullable value type T. If x is of reference or nullable value type then
// we cannot know, because again, the expression value could be null or it could be good. 

显然,如果已知(如您的示例)x 是一个non-null 表达式,则可以改进启发式算法。然而,正如 Eric Lippert writes in his blog,每个警告(实际上 - 每个编译器功能)都有成本,而且显然,Roslyn 开发人员认为此功能对于此版本来说不够重要。

所示,有 third-party 个解决方案填补了这个空白。