为什么通过接口提供dispose

时间:2016-04-15 10:56:53

标签: c# interface

根据MSDN,我已经在C#中对接口进行了一段时间的研究

"接口更适合于您的应用程序需要许多可能不相关的对象类型来提供某些功能的情况。"

https://msdn.microsoft.com/en-in/library/3b5b8ezk(v=vs.90).aspx

当实现Dispose()而不是使用Interface IDisposable时,我可以简单地定义3 Dispose()&的方法把它交给用户。我的问题是"为什么Microsoft创建了IDisposable接口,使用Interface实现Dispose()"的目的是什么。

这就是我的意思

//This method is used to release Managed Resources.
public void Dispose()
{
    this.Dispose();
}

//This method is used to release both managed & unmanaged Resources.
public void DisposeAll()
{
    this.Dispose();
    GC.SuppressFinalize(this);
    ReleaseUnmangedResources();
}

//This method is used to release only unmanaged Resources.
public void DisposeUnmanaged()
{
    ReleaseUnmangedResources();
}

如果这个问题太愚蠢或简单,我很抱歉。请帮助我理解界面。

2 个答案:

答案 0 :(得分:4)

IDisposable has special language support. Any object that implements IDisposable can be used as the subject of a using statement.

So,

using(var myDisposable = new ClassThatImplementsIDisposable())
{
      //do some stuff/ even throw an exception
}//myDisposable.Dispose() is automatically called, even if an exception happened.

using statements are a very (very very) useful way to ensure that stuff gets cleaned up without having to write a whole bunch of boilerplate to ensure that it happens (even in the case of exceptions).

By providing the IDisposable interface, you are advertising that the object needs disposing. Without it, disposal might be overlooked, and tools (such as FXCop) will not pick this up.

答案 1 :(得分:0)

通过实现IDisposable接口,您告诉您的班级用户,他应该在完成课程后调用Dispose()方法。 所以用户会做这样的事情:

DisposableClass c = new DisposableClass();
//doing something
if (c is IDisposable)
  c.Dispose();

此外,IDisposable对象在使用using语句创建时会自动处理。

using(var c = new DisposableClass())
{
  //doing something
} //c.Dispose() is called

在这种情况下,即使在使用块内抛出异常,也会调用Dispose()