为什么总是必要的实施有一个IDisposable的成员在对象上的IDisposable? [英] Why is it always necessary to implement IDisposable on an object that has an IDisposable member?

查看:174
本文介绍了为什么总是必要的实施有一个IDisposable的成员在对象上的IDisposable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,这是一个公认的规则,如果你有,有一个成员m是IDisposable的A类,A应该实现IDisposable的,它应该叫m.Dispose()里面它。



我找不到一个满意的原因是这种情况。



我理解的规则,如果你有非托管资源,你应该沿着IDisposable接口,这样如果用户没有明确调用Dispose,终结仍将GC在清理提供一个终结。



不过,与在地方规则,好像你不应该需要有这个问题是关于规则。例如...



如果我有一个类:

 类MYIMAGE {
私人图片_img;
...}



公约的国家,我应该有 MYIMAGE :IDisposable的。但是,如果图像一直遵循公约和执行终结,我不关心资源的及时释放,有什么意义呢?



更新



上找到什么,我试图让在的这里


解决方案

但如果图像遵循约定
和执行终结,我
不在乎
资源的及时释放,有什么意义呢?




那么,没有一个,如果你不关心及时释放,可以确保一次性对象写入正确的(说实话我从来没有作出这样的假设,即使不与MS的代码。你永远不知道什么时候被不慎滑倒)。问题的关键是,你应该小心,因为你永远不知道什么时候就会出现问题了。想想一个开放的数据库连接。离开它挂各处,意味着它未在池替代。如果你有几个要求进来一个你可以用完。



没有说你必须这样做,如果你不在乎。想想这样的方式,这就像在一个非管理程序释放变量。你不必,但它是高度可取的。如果没有其他原因从程序继承人没有想知道为什么它不照顾,然后尝试并清除它。


From what I can tell, it is an accepted rule that if you have a class A that has a member m that is IDisposable, A should implement IDisposable and it should call m.Dispose() inside of it.

I can't find a satisfying reason why this is the case.

I understand the rule that if you have unmanaged resources, you should provide a finalizer along with IDisposable so that if the user doesn't explicitly call Dispose, the finalizer will still clean up during GC.

However, with that rule in place, it seems like you shouldn't need to have the rule that this question is about. For instance...

If I have a class:

class MyImage{
  private Image _img;
  ... }

Conventions states that I should have MyImage : IDisposable. But if Image has followed conventions and implemented a finalizer and I don't care about the timely release of resources, what's the point?

UPDATE

Found a good discussion on what I was trying to get at here.

解决方案

But if Image has followed conventions and implemented a finalizer and I don't care about the timely release of resources, what's the point?

Then there isn't one, if you don't care about timely release, and you can ensure that the disposable object is written correct (in truth I never make an assumption like that, not even with MSs code. You never know when something accidentally slipped by). The point is that you should care, as you never know when it will cause a problem. Think about an open database connection. Leaving it hanging around, means that it isn't replaced in the pool. You can run out if you have several requests come in for one.

Nothing says you have to do it if you don't care. Think of it this way, it's like releasing variables in an unmanaged program. You don't have to, but it is highly advisable. If for no other reason the person inheriting from the program doesn't have to wonder why it wasn't taken care of and then try and clear it up.

这篇关于为什么总是必要的实施有一个IDisposable的成员在对象上的IDisposable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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