Resharper如何知道“表达总是如此”?

查看以下代码:

private void Foo(object bar) { Type type = bar.GetType(); if (type != null) // Expression is always true { } } 

Resharper声明type永远不会为null 。 这对我来说很明显,因为总会有一种类型的bar ,但是Resharper怎么知道呢? 怎么知道方法的结果永远不会为null

Type不是结构,所以不能这样。 如果方法是由我编写的,那么返回值肯定可以为null (不一定是GetType,而是其他东西)。

Resharper是否足够聪明,只知道该特定方法的结果永远不会为null ? (就像有一个已知的.Net方法的硬编码列表,永远不会返回null)

JetBrains完美地解释了ReSharper如何在其function列表中执行此操作。

链接摘要(这个特殊问题是关于NotNullAttribute ):

我们分析了.NET Framework类库以及NUnit Framework的很大一部分,并使用JetBrains.Annotations命名空间中的一组自定义属性,通过外部XML文件对其进行了注释,具体来说:

 StringFormatMethodAttribute (for methods that take format strings as parameters) InvokerParameterNameAttribute (for methods with string literal arguments that should match one of caller parameters) AssertionMethodAttribute (for assertion methods) AssertionConditionAttribute (for condition parameters of assertion methods) TerminatesProgramAttribute (for methods that terminate control flow) CanBeNullAttribute (for values that can be null) NotNullAttribute (for values that can not be null) UsedImplicitlyAttribute (for entities that should not be marked as unused) MeansImplicitUseAttribute (for extending semantics of any other attribute to mean that the corresponding entity should not be marked as unused) 

是的,它基本上了解一些众所周知的方法。 你也应该找到相同的字符串连接,例如:

 string x = null; string y = null; string z = x + y; if (z == null) { // ReSharper should warn about this never executing } 

现在通过代码合同可以获得相同的信息 – 我不知道JetBrains是否直接挂钩这些信息,有自己的数据库,还是两者的混合。

GetType不是virtual 。 您的假设很可能在您的上一次陈述中是正确的。

编辑:回答您的评论问题 – 它无法推断您的方法开箱即用。

object.GetType不是虚拟的,因此您object.GetType实现返回null值的版本。 因此,如果bar为null,您将获得NullReferenceException ,否则, type将永远不会为null。