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

时间:2017-01-23 13:57:32

标签: c# compiler-warnings reference-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)

3 个答案:

答案 0 :(得分:9)

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

此启发式的源代码可在此处找到: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是非空表达式,则可以改进启发式。但是,作为Eric Lippert writes in his blog,每个警告(事实上 - 每个编译器功能)都有成本,而且显然,Roslyn开发人员并不认为此功能对于此版本而言非常重要。

正如Thomas Weller's answer所示,有第三方解决方案填补了这一空白。

答案 1 :(得分:5)

因为它没有由Microsoft实现。但它是例如由JetBrains ReSharper实施。

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

Visual Studio

ReSharper显示4个警告:

ReSharper

答案 2 :(得分:-1)

is运算符无法重载。

  

请注意is运算符仅考虑引用转换,装箱转换和拆箱转换。其他转化,例如用户定义的转化,不予考虑。

来源:MSDN

相关问题