为什么Visual Studio在值类型上使用is
时会发出警告,但在引用类型上不会发生此警告?第1行和第2行提示警告,而第3行和第4行不提示。给出的表达式始终为提供的类型
if (5 is object)
if (new Point() is object)
if ("12345" is object)
if (new StringBuilder() is object)
为什么Visual Studio在值类型上使用is
时会发出警告,但在引用类型上不会发生此警告?第1行和第2行提示警告,而第3行和第4行不提示。给出的表达式始终为提供的类型
if (5 is object)
if (new Point() is object)
if ("12345" is object)
if (new StringBuilder() is object)
这是一个启发式和启发式,顾名思义,不完整的。
此启发式的源代码可以在这里找到: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显示,有第三方解决方案填补了这一空白。
伟大的答案:) –
虽然在Visual Studio中这很棒,但在使用'将警告视为错误'时不会中断构建。看到这个:http://stackoverflow.com/q/3361495/2557263 – Alejandro