prevent ReSharper的"可能的空引用异常"警告 [英] Prevent Resharper "Possible Null Reference Exception" warnings

查看:105
本文介绍了prevent ReSharper的"可能的空引用异常"警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个只读属性,并与那里的财产被实例化在构造函数中并标记为只读一个具体的类的接口。

Let's say I have an interface with a read-only property and and a concrete class where the property is instantiated in the constructor and marked as read-only.

internal interface IExample
{
    ObservableCollection<string> Items { get; }
}


internal class Example : IExample
{ 
    private readonly ObservableCollection<string> _items;

    public Example()
    {
       _items = new ObservableCollection<string>();
    }

    public ObservableCollection<string> Items
    {
       get { return _items; }
    }
}

当我使用ReSharper的警告我的界面,我可能在调用code可能的空引用。

When I use the interface Resharper warns me that I might have a possible null reference in calling code.

public class ExampleWithWarnings
{
    public void Show()
    {
       IExample example = new Example();

       // resharper warns about null reference
       example.Items.Add( "test" );
    }
}

我知道,根据定义,接口不保证该属性将有一个值。 (我也认识到,在接口上性能不理想)。但我知道这个属性将始终有一个值。

I realize that by definition the interface doesn't guarantee that the property will have a value. (I also recognize that properties on interfaces aren't ideal). But I know this property will always have a value.

有没有什么神奇的属性,我可以把将prevent ReSharper的从显示警告的接口上?我宁愿没有装饰类的所有用法与禁用编译警告。

Is there any magic attribute that I can put on the interface that would prevent Resharper from showing a warning? I'd rather not have to decorate all usages of the class with a disable pragma warning.

推荐答案

是的,有一个属性,你可以使用: JetBrains.Annotations.NotNullAttribute 。但你并不需要添加一个引用ReSharper的在你的项目。你可以用自己的实现:打开ReSharper的选项,然后在code检验> code注解,你会发现一个复制默认实现到剪贴板。现在只需粘贴到项目中的code文件。你甚至可以改变的空间。

Yes, there is an attribute you can use: JetBrains.Annotations.NotNullAttribute. But you don't need to add a reference to ReSharper in your project. You can use your own implementation: open the ReSharper options, and under Code Inspection > Code Annotations you will find a "Copy default implementation to clipboard". Now just paste that into a code file in your project. You can even change the namespace.

然后就打在接口属性的属性。

And then slap the attribute in the interface property.

您也应该有在code检验>设置一看,挑选假定实体可以为空...当实体被显式地标记CanBeNull属性,或者检查空。这样,你只得到了成员警告你明确标记为麻烦。

You should also have a look under Code Inspection > Settings and pick "Assume entity can be null... when entity is explictly marked with CanBeNull attribute, or checked for null". This way you only get warnings in the members you explicit mark as troublesome.

这篇关于prevent ReSharper的&QUOT;可能的空引用异常&QUOT;警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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