Declare IDisposable for the class or interface?

2019-02-04 05:39发布

Starting from the follwing situation:

public interface ISample
{
}

public class SampleA : ISample
{
   // has some (unmanaged) resources that needs to be disposed
}

public class SampleB : ISample
{
   // has no resources that needs to be disposed
}

The class SampleA should implement the interface IDisposable for releasing resources. You could solve this in two ways:

1. Add the required interface to the class SampleA:

public class SampleA : ISample, IDisposable
{
   // has some (unmanaged) resources that needs to be disposed
}

2. Add it to the interface ISample and force derived classes to implement it:

public interface ISample : IDisposable
{
}

If you put it into the interface you force any implementation to implement IDisposable even if they have nothing to dispose. On the other hand, it is very clear to see that the concrete implementation of an interface requires a dispose/using block and you don't need to cast as IDisposable for cleaning up. There might be some more pros/cons in both ways... why would you suggest to use one way preferred to the other?

7条回答
三岁会撩人
2楼-- · 2019-02-04 06:13

If you apply the using(){} pattern to all your interfaces it's best to have ISample derive from IDisposable because the rule of thumb when designing interfaces is to favor "ease-of-use" over "ease-of-implementation".

查看更多
登录 后发表回答