How to get rid of CA2000 warning when ownership is transferred?

后端 未结 4 1863
情深已故
情深已故 2020-12-09 17:08

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

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


        
4条回答
  •  执笔经年
    2020-12-09 17:53

    I know this is sample code, and so whether this workaround would work in your real code, I couldn't say.

    In this particular case, if you move the object creation code into it's own method, that returns the new Item, then the warning will disappear, e.g. change:

    public void Initialize()
     {
      var item1 = new Item(); // no warning
      itemCollection.Add(item1);
    
      var item2 = CreateItem(); // CA2000 no longer appears
      Add(item2);
    
      var item3 = new Item(); // CA2000: call Dispose on object item3
      itemContainer.Add(item3);
     }
    
     private Item CreateItem()
     {
      return new Item();
     }
    

    Obviously, the CreateItem method could be passed arbitrary parameters to pass to the Item constructor.

    Edit

    Having seen Henrik's answer, and the response on Connect, all I can say is bletch. There's no guarantee that an ICollection implementation also implements IDisposable, and whilst his posted example does implement IDisposable, apparently that's not required to shut up the code analysis (I'd have been somewhat okay if you had to implement both). A class implementing ICollection but not implementing IDisposable is highly unlikely to deal with disposing of contained objects correctly.

提交回复
热议问题