我不太了解使用/一次性对象的工作原理 [英] I don't quite understand the workings of using/Disposable objects

查看:68
本文介绍了我不太了解使用/一次性对象的工作原理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问了一个有关退还一次性用品( IDisposable)来自函数的对象,但我认为如果我在那里提出这个问题,我会弄乱讨论.

I asked a question regarding returning a Disposable (IDisposable) object from a function, but I thought that I would muddle the discussion if I raised this question there.

我创建了一些示例代码:

I created some sample code:

class UsingTest
{
    public class Disposable : IDisposable
    {
        public void Dispose()
        {
            var i = 0;
            i++;
        }
    }
    public static Disposable GetDisposable(bool error)
    {
        var obj = new Disposable();
        if (error)
            throw new Exception("Error!");
        return obj;
    }
}

我故意用这种方式编码,因为然后我打电话给

I coded it this way deliberately, because then I call:

using (var tmp = UsingTest.GetDisposable(true)) { }

使用调试器,我注意到Dispose方法从不执行,即使我们已经实例化了Disposable对象.如果我正确理解Dispose的目的,如果该类实际上已经打开了句柄之类的东西,那么我们在完成它们后就不会立即关闭它们.

Using the debugger, I notice that the Dispose method never executes, even though we've already instantiated a Disposable object. If I correctly understand the purpose of Dispose, if this class actually had opened handles and the like, then we would not close them as soon as we had finished with them.

我问这个问题是因为这种行为符合我的预期,但是在回答相关问题时,人们似乎表示using会照顾好一切.

I ask this question because this behavior aligns with what I would expect, but in the answers to the related question, people seemed to indicate that using would take care of everything.

如果using仍然可以解决所有这些问题,那么有人可以解释我所缺少的吗?但是,如果此代码确实可能导致资源泄漏,您将如何建议我编写GetDisposable代码(条件是我必须实例化IDisposable对象并运行可能在return语句之前引发异常的代码)?

If using still somehow takes care of all of this, could someone explain what I'm missing? But, if this code could indeed cause resource leak, how would you suggest I code GetDisposable (with the condition that I must instantiate the IDisposable object and run code which could throw an exception prior to the return statement)?

推荐答案

根据您想要GetDisposable的语义,这可能是我将其实现的方式:

Depending upon what semantics you want for GetDisposable, this is probably how I would implement it:

public static Disposable GetDisposable(bool error)
{
    var obj = new Disposable();

    try
    {
        if (error)
            throw new Exception("Error!");

        return obj;
    }
    catch (Exception)
    {
        obj.Dispose();
        throw;
    }
}

这篇关于我不太了解使用/一次性对象的工作原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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