为什么在对值类型使用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)
答案 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)
答案 2 :(得分:-1)