加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在每个函数中使用语句 – >通过适当的清理转换为类字段

发布时间:2020-12-15 18:07:45 所属栏目:百科 来源:网络整理
导读:基本上我有一些看起来像这样的函数: class MyClass{ void foo() { using (SomeHelper helper = CreateHelper()) { // Do some stuff with the helper } } void bar() { using (SomeHelper helper = CreateHelper()) { // Do some stuff with the helper } }
基本上我有一些看起来像这样的函数:
class MyClass
{
    void foo()
    {
       using (SomeHelper helper = CreateHelper())
       {
           // Do some stuff with the helper
       }
    }

    void bar()
    {
        using (SomeHelper helper = CreateHelper())
        {
           // Do some stuff with the helper
        }
    }
}

假设我可以在每个函数中使用相同的资源而不是一个不同的[实例],那么在清理方面是否可以做到这样做?

class MyClass
{
    SomeHelper helper = CreateHelper();

    // ...foo and bar that now just use the class helper....

    ~MyClass()
    {
      helper.Dispose();
    }
}

解决方法

不,不要添加析构函数(Finalizer).

您可以重用资源,但您的类必须实现IDisposable.

sealed class MyClass : IDisposable
{
    SomeHelper helper = CreateHelper();

    // ...foo and bar that now just use the class helper....

    //~MyClass()
    public void Dispose()    
    {
      helper.Dispose();
    }                         
}

现在你必须在using块中使用MyClass实例.它本身已成为一种托管资源.

析构函数是没有用的,每当收集MyClass实例时,关联的帮助器对象也将在同一个集合中.但是,使用析构函数仍会产生相当大的开销.

IDisposable的standard pattern使用虚拟void Dispose(bool disposing)方法,但在密封类时,您可以使用上面的简约实现.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读