现IDisposable接口时Dispose方法的内容应该是什么

现IDisposable接口时Dispose方法的内容应该是什么

本文介绍了C#:实现IDisposable接口时Dispose方法的内容应该是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个实现 IDisposable 接口的类,VisualStudio IDE为我带来了Dispose方法.我想知道我应该在Dispose方法中编写什么代码,以便它可以处理我的内存管理或应该做的事情.

I created a class which implements IDisposable interface and VisualStudio IDE brought the Dispose method for me. I am wondering what code i should write inside the Dispose method so that it will take care of my memory management or whatever stuff it should do.

public class ESNVerification : IDisposable
{

  public bool Save(string a,string b)
  {
    //Save the data to table
    return true;
  }

  public void Dispose()
  {
       throw new NotImplementedException();
       // Really what i should do here  ?
  }
}

推荐答案

我建议三个简单规则,说明如何实现IDisposable;在这里简化:

I recommend Three Simple Rules for how to implement IDisposable; simplified here:

  • 规则1:请勿这样做(除非您需要这样做).只有两种情况需要实现IDisposable:该类拥有一个非托管资源该类拥有一个托管(IDisposable)资源.
  • >
  • 规则2:对于拥有托管资源的类,请实现IDisposable(而不是终结器). IDisposable的此实现仅应为每个拥有的资源调用Dispose.该类不应具有终结器.
  • 规则3:对于拥有单个非托管资源的类,请同时实现IDisposable和终结器.
  • Rule 1: Don't do it (unless you need to). There are only two situations when IDisposable does need to be implemented: The class owns an unmanaged resource or The class owns managed (IDisposable) resources.
  • Rule 2: For a class owning managed resources, implement IDisposable (but not a finalizer). This implementation of IDisposable should only call Dispose for each owned resource. The class should not have a finalizer.
  • Rule 3: For a class owning a single unmanaged resource, implement both IDisposable and a finalizer.

这篇关于C#:实现IDisposable接口时Dispose方法的内容应该是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 03:03