我应该如何继承IDisposable的?

编程入门 行业动态 更新时间:2024-10-09 00:51:28
本文介绍了我应该如何继承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的?

本文发布于:2023-11-07 15:39:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1566840.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:IDisposable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!