谁应该调用Dispose IDisposable的对象时传递到另一个对象? [英] Who should call Dispose on IDisposable objects when passed into another object?

查看:162
本文介绍了谁应该调用Dispose IDisposable的对象时传递到另一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有解决谁应该调用任何指导或最佳实践的Dispose()一次性对象时,他们已经传递到另一个对象的方法或constuctor?

Is there any guidance or best practices around who should call Dispose() on disposable objects when they have been passed into another object's methods or constuctor?

下面是几个例子,以我的意思。

Here's a couple of examples as to what I mean.

IDisposable的对象传递给方法(如果它处理它,一旦它做什么?):

IDisposable object is passed into a method (Should it dispose of it once its done?):

public void DoStuff(IDisposable disposableObj)
{
    // Do something with disposableObj
    CalculateSomething(disposableObj)

    obj.Dispose();
}

IDisposable的对象传递给方法和参考保持(如果它处理它时 MyClass的设置?):

public class MyClass : IDisposable
{
    private IDisposable _disposableObj = null;

    public void DoStuff(IDisposable disposableObj)
    {
        _disposableObj = disposableObj;
    }

    public void Dispose()
    {
        _disposableObj.Dispose();
    }
}

我目前认为在第一个例子中的来电 DoStuff()应该处理的对象,因为它可能创建的对象。但在第二个例子中,感觉就像 MyClass的应该处理的对象,因为它使一个参考吧。这里的问题是,调用类可能不知道 MyClass的一直保持一个参考,因此,可能会决定之前 MyClass的已使用完毕。 是否有这种情形的任何标准的规则?如果有,它们有什么不同的时候一次性对象被传递到构造函数?

I'm currently thinking that in the first example the caller of DoStuff() should dispose of the object as it probably created the object. But in the second example it feels like MyClass should dispose of the object as it keeps a reference to it. The problem with this is that the calling class might not know MyClass has kept a reference and therefore might decide to dispose of the object before MyClass has finished using it. Are there any standard rules for this sort of scenario? If there are, do they differ when the disposable object is being passed into a constructor?

推荐答案

一个一般的规则是,如果你创建(或获得所有权)的对象,然后它是你的责任,处理它。这意味着,如果你收到一个一次性的对象,在方法或构造函数的参数,你通常应该不会出售它。

A general rule is that if you created (or acquired ownership of) the object then it is your responsibility to dispose it. This means that if you receive a disposable object as a parameter in a method or constructor you usually should not dispose it.

请注意,某些类在.NET框架的的处理,他们收到的参数对象。例如设置一的StreamReader 还部署底层

Note that some classes in the .NET framework do dispose objects that they received as parameters. For example disposing a StreamReader also disposes the underlying Stream.

这篇关于谁应该调用Dispose IDisposable的对象时传递到另一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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