What is the relationship between the use keyword and the IDisposable interface?

If I use a keyword using, do I still need to implement IDisposable?

+5
source share
7 answers

If you use usingstatement , the nested type should already implement IDisposable, otherwise the compiler will throw an error. Therefore, we consider the IDisposable implementation as a prerequisite for use.

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. 
}
+12

.

:

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 .

+12

. "using" , IDisposable.

: using, invpose Dispose, . , using try-finally, Dispose finally.

+5

, using ... ( msdn)

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

: .

, , , , , ...

  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.
}
+4

. , , IDisposable , , .

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

, IDisposable , using. using Dispose , , Dispose. block, .

using , Dispose , . , try, finally; , , using .

+2

using , , using, IDisposable

+1

IDisposable . using() , IDisposable, :

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

All Articles