问题描述
从以下情况开始:
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
}
类SampleA应该实现IDisposable接口以释放资源。
您可以通过两种方式解决此问题:
The class SampleA should implement the interface IDisposable for releasing resources.You could solve this in two ways:
1。将所需接口添加到类SampleA中:
public class SampleA : ISample, IDisposable
{
// has some (unmanaged) resources that needs to be disposed
}
2。将其添加到接口ISample中,并强制派生类对其进行实现:
public interface ISample : IDisposable
{
}
如果将其放入接口中,则会强制任何实现IDisposable的实现即使他们没有什么可处置的。另一方面,很清楚地看到,接口的具体实现需要一个处理/使用块,并且不需要将其强制转换为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?
推荐答案
如果将 using(){}
模式应用于所有接口,则最好让 ISample
从 IDisposable
是因为设计界面时的经验法则是易于使用 胜过易于实施 。
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".
这篇关于为类或接口声明IDisposable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!