在一个密封类实现了IDisposable [英] Implementing IDisposable on a sealed class

查看:166
本文介绍了在一个密封类实现了IDisposable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不认为这个问题已经被问过。我的最佳方式有点混乱落实的IDisposable 在一个密封类,具体地说,就是密封类,没有从基类继承。 (也就是说,一个纯粹的密封类,这是我的组成部分。)

I don't think this question has been asked before. I'm a bit confused on the best way to implement IDisposable on a sealed class—specifically, a sealed class that does not inherit from a base class. (That is, a "pure sealed class" which is my made up term.)

也许有些你同意我的,执行该准则 IDisposable的都非常混乱。不过,我想知道,我打算的方式来实施的IDisposable 是充分的,安全的。

Perhaps some of you agree with me in that the guidelines for implementing IDisposable are very confusing. That said, I want to know that the way I intend to implement IDisposable is sufficient and safe.

我]丢一些的P / Invoke代码分配一个的IntPtr Marshal.AllocHGlobal 自然,我想干净处置非托管的内存,我创建的。所以我想使用System.Runtime.InteropServices像这样

I'm doing some P/Invoke code that allocates an IntPtr through Marshal.AllocHGlobal and naturally, I want to cleanly dispose of the unmanaged memory I've created. So I'm thinking of something like this

using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential)]
public sealed class MemBlock : IDisposable
{
     IntPtr ptr;
     int length;

     MemBlock(int size)
     {
           ptr = Marshal.AllocHGlobal(size);
           length = size;
     }

     public void Dispose()
     {
          if (ptr != IntPtr.Zero)
          {
               Marshal.FreeHGlobal(ptr);
               ptr = IntPtr.Zero;
               GC.SuppressFinalize(this);
          }
     }

     ~MemBlock()
     {
           Dispose();
     }    
}



我假设,因为 MemBlock 完全密封,并从另一个类实施虚保护的Dispose(BOOL处置)是没有必要永远派生。

I'm assuming that because MemBlock is completely sealed and never derives from another class that implementing a virtual protected Dispose(bool disposing) is not necessary.

此外,为终结严格必要吗?所有的想法欢迎。

Also, is the finalizer strictly necessary? All thoughts welcome.

推荐答案

终结是必要的备用机制,最终免费非托管资源,如果你忘了打电话的Dispose

The finalizer is necessary as a fallback mechanism to eventually free unmanaged resources if you forgot to call Dispose.

没有,你不应该声明虚拟方法在密封类。它不会编译的。此外,它不建议在密封类申报新的保护成员。

No, you shouldn't declare a virtual method in a sealed class. It wouldn't compile at all. Also, it's not recommended to declare new protected members in sealed classes.

这篇关于在一个密封类实现了IDisposable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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