c# - 已检查 null 时 ReSharper 可能出现 Null 异常

标签 c# resharper extension-methods nullreferenceexception code-contracts

这是带有 Visual Studio 2012 的 ReSharper 7。下面是示例

// This code works fine and as expected and ReShrper is happy with it
if (!string.IsNullOrWhiteSpace(extension) && extension.Length == 3)
{
    // do something
}

// ReSharper highlights "extension" in extension.Length with "Possible 'System.NullReferenceException'"
if (!extension.IsNullOrWhiteSpace() && extension.Length == 3)
{
    // do something
}

并且,我创建了以下扩展方法:

public static class StringExtensions
{
    public static bool IsNullOrWhiteSpace(this string s)
    {
        return string.IsNullOrWhiteSpace(s);
    }
}

我查看了 String.IsNullOrWhiteSpace 的反射代码,它没有任何相关代码或属性会向 R# 突出显示检查已验证。这是在 R# 中硬编码的吗?

我查看了 Code Contracts,但我不确定它对我的情况是否有帮助。

您是否有向 ReSharper 证明检查条件已通过我的扩展方法验证的解决方法?

最佳答案

适用于 Resharper 7 及更高版本

[ContractAnnotation("null=>true")]
public static bool IsNullOrWhiteSpace(this string s)

您的项目不会知道 ContractAnnotation 是什么。您需要将其添加到您的项目中。首选方法是通过 nuget:

PM> Install-Package JetBrains.Annotations

或者,您可以直接将源代码嵌入到您的项目中:

Resharper -> Options -> Code Annotations -> Copy default implementation to clipboard

然后将其粘贴到一个新文件中,例如 Annotations.cs。 ContractAnnotation 定义存在于该文件中。有关 ContractAnnotation 的官方文章,请参阅 here


上一个答案(针对非 R#7 版本)

Is this hardcoded in R#?

不,Resharper 使用外部注释来提供此功能。 This article应该回答您的所有问题,包括为您的 IsNullOrWhiteSpace 方法提供您自己的外部注释的解决方案。

例子

注意:外部注释似乎只适用于引用的库;如果您的引用来自项目,则不会提取外部注释;这不太理想

假设您的扩展方法位于名为 TempExtensions 的类中,该类本身位于名为 ClassLibrary1 的程序集中

您需要在此位置添加一个新文件

C:\Program Files (x86)\JetBrains\ReSharper\v7.0\Bin\ExternalAnnotations.NETFramework.ExternalAnnotations\ClassLibrary1\ClassLibrary1.xml

xml的内容应该包含:

<assembly name="ClassLibrary1">
  <member name="M:ClassLibrary1.TempExtensions.IsNullOrWhiteSpace(System.String)">
    <attribute ctor="M:JetBrains.Annotations.ContractAnnotationAttribute.#ctor(System.String,System.Boolean)">
        <argument>null=&gt;true</argument>
        <argument>true</argument>
    </attribute>
  </member>
</assembly>

关于c# - 已检查 null 时 ReSharper 可能出现 Null 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12026649/

相关文章:

c# - .NET4.5 中异步 POST 方法的 HttpResponseMessage 异常

linq - Resharper 是否在此处不必要地警告我访问修改后的闭包?

c# - ReSharper 5 禁用解析 View

c# - 扩展方法未设置值

swift - 在 Swift 中,如何创建 String 的后代?我在尝试这样做时收到错误 "Inheritance from non-protocol, non-class type ' String'"

c# - 是否可以使用 2.0 框架创建扩展方法?

c# - 在不考虑 Linq 中任何格式的情况下比较电话号码与实体并检查性能

c# - 在 C# 中解析 Xsd 的属性

c# - 使用 jQuery 将多个参数发布到 Web API

c# - Web 应用程序中对 System.Windows.Forms 的资源和引用