How do you prevent IDisposable from spreading to all your classes?

后端 未结 7 635
抹茶落季
抹茶落季 2020-12-07 10:28

Start with these simple classes...

Let\'s say I have a simple set of classes like this:

class Bus
{
    Driver busDriver = new Driver();
}

class          


        
7条回答
  •  感情败类
    2020-12-07 10:41

    In terms of correctness, you can't prevent the spread of IDisposable through an object relationship if a parent object creates and essentially owns a child object which must now be disposable. FxCop is correct in this situation and the parent must be IDisposable.

    What you can do is avoid adding an IDisposable to a leaf class in your object hierarchy. This is not always an easy task but it's an interesting exercise. From a logical perspective, there is no reason that a ShoeLace needs to be disposable. Instead of adding a WaitHandle here, is it also possible to add an association between a ShoeLace and a WaitHandle at the point it's used. The simplest way is through an Dictionary instance.

    If you can move the WaitHandle into a loose association via a map at the point the WaitHandle is actually used then you can break this chain.

提交回复
热议问题