using关键字和IDisposable接口之间有什么关系?

如果我使用using关键字,我还需要实现IDisposable吗?

如果使用using语句,则封闭类型必须已实现IDisposable否则编译器将发出错误。 因此,将IDisposable实现视为使用的先决条件。

如果要在自定义类上使用using语句,则必须为其实现IDisposable 。 然而,这是一种落后的做法,因为没有意义这样做。 只有当你有一些像处理非托管资源一样的东西时才应该实现它。

 // To implement it in C#: class MyClass : IDisposable { // other members in you class public void Dispose() { // in its simplest form, but see MSDN documentation linked above } } 

这使您能够:

 using (MyClass mc = new MyClass()) { // do some stuff with the instance... mc.DoThis(); //all fake method calls for example mc.DoThat(); } // Here the .Dispose method will be automatically called. 

实际上和写作一样:

 MyClass mc = new MyClass(); try { // do some stuff with the instance... mc.DoThis(); //all fake method calls for example mc.DoThat(); } finally { // always runs mc.Dispose(); // Manual call. } 

你不能没有另一个。

当你写:

 using(MyClass myObj = new MyClass()) { myObj.SomeMthod(...); } 

编译器将生成如下内容:

 MyClass myObj = null; try { myObj = new MyClass(); myObj.SomeMthod(...); } finally { if(myObj != null) { ((IDisposable)myObj).Dispose(); } } 

因此,在using关键字时可以看到,假设/要求实现IDisposable。

你是混乱的事情。 您只能在实现IDisposable的内容上使用“using”关键字。

编辑:如果使用using关键字,则不必明确调用Dispose,它将在using块的末尾自动调用。 其他人已经发布了如何将using语句转换为try-finally语句的示例,并在finally块中调用Dispose。

是的,using关键字是这种模式的语法糖…(来自msdn)

  Font font1 = new Font("Arial", 10.0f); try { byte charset = font1.GdiCharSet; } finally { if (font1 != null) ((IDisposable)font1).Dispose(); } 

编辑:一个有用的例子。

当你发现你正在最后一节中做一些事情时,例如将Cursor设置为等待光标后重置为默认值,这是这个模式的候选者……

  public class Busy : IDisposable { private Cursor _oldCursor; private Busy() { _oldCursor = Cursor.Current; } public static Busy WaitCursor { get { Cursor.Current = Cursors.WaitCursor; return new Busy(); } } #region IDisposable Members public void Dispose() { Cursor.Current = _oldCursor; } #endregion } 

被称为……

 using(Busy.WaitCursor) { // some operation that needs a wait cursor. } 

使用只会丢弃一次性物品。 因此,围绕未实现IDisposable的对象包装使用块实际上是无用的 ,实际上会导致编译器错误。

http://msdn.microsoft.com/en-us/library/yh598w02.aspx

通常,当您使用IDisposable对象时,您应该在using语句中声明并实例化它。 using语句以正确的方式调用对象上的Dispose方法,并且一旦调用Dispose,它也会导致对象本身超出范围。 在using块中,该对象是只读的,不能修改或重新分配。

using语句确保即使在对象上调用方法时发生exception,也会调用Dispose。 您可以通过将对象放在try块中然后在finally块中调用Dispose来实现相同的结果; 实际上,这就是编译器如何翻译using语句。

您必须实现IDisposable才能使用。 如果您尝试在未实现IDisposable的类型上使用using(),则会出现以下编译时错误:

 error CS1674: 'SomeType': type used in a using statement must be implicitly convertible to 'System.IDisposable' 

using关键字已经实现,因此如果使用using关键字,则不必调用IDisposable