prevent ReSharper的"可能的空引用异常"警告异常、prevent、ReSharper、QUOT

2023-09-05 23:15:54 作者:欲戴王冠必承其重

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

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.

 
精彩推荐
图片推荐