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

标签 c# .net 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
        }
    }
}

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

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 block 中使用 MyClass 实例。它本身已成为一个托管资源

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

standard pattern对于 IDisposable 使用 virtual void Dispose(bool disposing) 方法,但是在制作类 sealed 时,您可以使用上面的简约实现。

关于c# - 在每个函数中使用语句 -> 通过适当的清理转换为类字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8231661/

相关文章:

c# - 如果没有通过 using block 实例化实现 IDisposable 的类是否有方法抛出异常?

c# - 程序强制关闭时 "using"是否 block 释放资源

c# - 测试继承的 C# 类

c# - 将文件读入字节数组与字符串不同

c# - 分割字符串时获取元素的最后一部分

.net - 多个 .NET 进程内存占用

c# - 为什么 GridView 没有显示在浏览器上?

c# - 使用集成 Windows 身份验证时提示输入登录详细信息

c# - 有没有办法在不显示 gui 窗口的情况下运行 c# 表单应用程序(如控制台应用程序)

c# - 会为匿名变量调用 dispose 吗?