如何摆脱CA2000警告时所有权发生转移? [英] How to get rid of CA2000 warning when ownership is transferred?

查看:165
本文介绍了如何摆脱CA2000警告时所有权发生转移?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下code生成两个CA2000警告(等等,但是这不是重点)。

The following code generates two CA2000 warnings (among others, but that's not the point).

public sealed class Item: IDisposable
{
    public void Dispose() {}
}

public sealed class ItemContainer
{
    public void Add(Item item)
    {
    }
}

public sealed class Test: IDisposable
{
    private ICollection<Item> itemCollection;
    private ItemContainer itemContainer;

    private void Add(Item item)
    {
        itemCollection.Add(item);
    }

    public void Initialize()
    {
        var item1 = new Item(); // no warning
        itemCollection.Add(item1);

        var item2 = new Item(); // CA2000: call Dispose on object item2
        Add(item2);

        var item3 = new Item(); // CA2000: call Dispose on object item3
        itemContainer.Add(item3);
    }

    public void Dispose() {}
}

请注意,有对ITEM1不会产生警告。看来,code分析假定的ICollection 将采取项目责任,并最终出售它。

Note that there is no warning generated for item1. It seems, Code Analysis assumes the ICollection will take responsibility of the item and eventually dispose it.

有没有一种方法,以纪念我的添加方法,从而使警报消失?

Is there a way to mark my Add methods, so that the warning goes away?

我在寻找类似 ValidatedNotNullAttribute 为CA1062的东西。

I'm looking for something similar to ValidatedNotNullAttribute for CA1062.

编辑:要清楚:这不是我真正的code。在现实code,一切都妥善处置。

to make it clear: this is not my real code. In the real code, everything is properly disposed.

这只是CA不承认呼叫我的添加方法转移所有权。
我想它来治疗它把 ICollection.Add

It's just that CA does not recognize that the call to my Add methods transfers ownership. I would like it to treat my Add methods in the same way it treats ICollection.Add.

在同一范围内处置不是一个选项。

Disposing in the same scope is not an option.

推荐答案

我也问了这个在connect.microsoft.com,这是他们说什么:

I also asked this at connect.microsoft.com and this is what they answered:

您可以通过具有容器/集合对象,增加了一次性对象实现的ICollection或ICollection的&LT解决该问题; T&取代。执行添加该方法还必须有名称开头添加。

和果然:当Test类实现的ICollection&LT;项目&gt ;,然后报警消失。这是有问题的情况下的可接受的解决方案。但它仍然是一个悬而未决的问题做什么,当它不适合执行ICollection的指示所有权转让。

And sure enough: when class Test implements ICollection<Item>, then the warning goes away. This is an acceptable solution for the case in question. But it's still an open question what to do, when it's not appropriate to implement ICollection to indicate transfer of ownership.

public sealed class Test: IDisposable, ICollection<Item>
{
    public void Initialize()
    {
        var item1 = new Item(); // no warning
        itemCollection.Add(item1);

        var item2 = new Item(); // no warning
        ((ICollection<Item>)this).Add(item2);

        var item3 = new Item(); // no warning
        AddSomething(item3);
    }

    //... implement ICollection and Method AddSomething
}

这篇关于如何摆脱CA2000警告时所有权发生转移?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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