如何ReSharper的专有"表达始终是真实的"? [英] How Does Resharper Know "Expression is always true"?

查看:161
本文介绍了如何ReSharper的专有"表达始终是真实的"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看看下面的代码:

 私人无效美孚(对象吧)
{
型键入= bar.GetType();

如果(型!= NULL)//表达总是真
{
}
}

ReSharper的索赔键入绝不会。这是显而易见的我,因为那里总是将成为 A型,但如何ReSharper的知道吗?它怎么能知道一个方法的结果决不会



键入不是一个结构,因此不能说。如果该方法是由我写的则返回值可以肯定(不一定的G​​etType,而是别的东西)。



时ReSharper的够聪明的知道,只有特定的方法,结果将永远? (像有它永远不会返回null已知的.NET方法硬编码的列表)


解决方案

JetBrains的完美解释了ReSharper的是如何做到这一点在他们的功能列表



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




我们已经分析一个伟大的份额.NET Framework类库,以及NUnit的框架,并注明它通过外部XML文件,使用一组自定义从JetBrains.Annotations命名空间属性,具体如下:




  StringFormatMethodAttribute(对于以格式字符串作为参数的方法)
InvokerParameterNameAttribute(用于字符串参数的方法应符合来电者之一参数)
AssertionMethodAttribute(断言方法)
AssertionConditionAttribute(为断言方法条件参数)
TerminatesProgramAttribute(对于终止控制流的方法)
CanBeNullAttribute(对于值可以为空)
NotNullAttribute(为值不能为null)
UsedImplicitlyAttribute(对于实体不应该被标记为未使用)
MeansImplicitUseAttribute(用于扩展任何其他属性的语义意味着相应的实体不应该被标记为未使用)


Check out the following code:

private void Foo(object bar)
{
   Type type = bar.GetType();

    if (type != null) // Expression is always true
    {   
    }
}

Resharper claims type will never be null. That's obvious to me because there's always going to be a type for bar, but how does Resharper know that? How can it know that the result of a method will never be null.

Type is not a struct so it can't be that. And if the method were written by me then the return value could certainly be null (not necessarily GetType, but something else).

Is Resharper clever enough to know that for only that particular method the result will never be null ? (Like there's a hard coded list of known .Net methods which will never return null)

解决方案

JetBrains perfectly explains how ReSharper does this in their features list.

Summary from link (this particular question is about NotNullAttribute):

We have analyzed a great share of .NET Framework Class Library, as well as NUnit Framework, and annotated it through external XML files, using a set of custom attributes from the JetBrains.Annotations namespace, specifically:

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)

这篇关于如何ReSharper的专有"表达始终是真实的"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆