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

Jos*_*eld 6 .net c# idisposable

基本上我有一些看起来像这样的函数:

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

class MyClass
{
    SomeHelper helper = CreateHelper();

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

    ~MyClass()
    {
      helper.Dispose();
    }
}
Run Code Online (Sandbox Code Playgroud)

Hen*_*man 8

不,添加一个析构函数(终结).

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

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

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

    //~MyClass()
    public void Dispose()    
    {
      helper.Dispose();
    }                         
}
Run Code Online (Sandbox Code Playgroud)

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

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

IDisposable 的标准模式使用virtual void Dispose(bool disposing)方法,但在创建类时,sealed您可以使用上面的简约实现.