我应该如何继承IDisposable的? [英] How should I inherit IDisposable?

查看:436
本文介绍了我应该如何继承IDisposable的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类的名称已被更改,以保护无辜

如果我有一个名为ISomeInterface的接口。我也有继承接口的Firstclass和二等类。的Firstclass使用,必须设置资源。二等没有。

If I have an interface named ISomeInterface. I also have classes that inherit the interface, FirstClass and SecondClass. FirstClass uses resources that must be disposed. SecondClass does not.

所以,问题是,我应该在哪里自IDisposable继承?下面的两个选择似乎不太理想:

So the question is, where should I inherit from IDisposable? Both of the following options seem less than ideal:

1)请的Firstclass继承了IDisposable 。然后,与ISomeInterfaces交易的任何代码都必须知道是否要处理掉。这闻起来像紧耦合给我。

1) Make FirstClass inherit IDisposable. Then, any code that deals with ISomeInterfaces will have to know whether or not to dispose of them. This smells like tight coupling to me.

2)请ISomeInterface继承了IDisposable 。然后,从它继承的类必须实现IDisposable,即使有什么处置。 Dispose方法将基本上是除了征求意见的空白。

2) Make ISomeInterface inherit IDisposable. Then, any class that inherits from it must implement IDisposable, even if there is nothing to dispose. The Dispose method would essentially be blank except for comments.

#2似乎是正确的选择我,但如果有其他选择,我想知道。

#2 seems like the correct choice to me, but I'm wondering if there are alternatives.

推荐答案

如果有合理的机会,一个抽象的实体(接口或抽象类)的 的可能需要一次性的,它应该实现它。 ,例如不本身需要的IDisposable ,也没有的IEnumerator< T> ...

If there is a reasonable chance that an abstract entity (interface or abstract class) might need to be disposable, it should implement it. Stream, for example doesn't itself need IDisposable, nor does IEnumerator<T>...

这是抽象基类,可以更简单,因为你可以有一个默认的(空)的实施的Dispose()那么,可能终结/的Dispose(布尔)模式,即

An abstract base class may be simpler, as you can have a default (empty) implementation of Dispose() then, and possibly the finalizer / Dispose(bool) pattern, i.e.

void IDisposable.Dispose() { Dispose(true); GC.SuppressFinalize(this); }
protected virtual void Dispose(bool disposing) {}
~BaseType() {Dispose(false);}

这篇关于我应该如何继承IDisposable的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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