Not*_*per 9 c# reference-type compiler-warnings
为什么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)
Run Code Online (Sandbox Code Playgroud)
根据定义,它是一种启发式和启发式,是不完整的.
这个启发式的源代码可以在这里找到:Roslyn来源: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.
Run Code Online (Sandbox Code Playgroud)
显然,如果已知(如在您的示例中)x非空表达式,则可以改进启发式.但是,正如Eric Lippert在他的博客中写道的那样,每一个警告(事实上 - 每个编译器功能)都有成本,而且显然,Roslyn开发人员并不认为这个特性对于这个版本来说非常重要.
正如Thomas Weller的回答所示,有第三方解决方案填补了这一空白.