Inc*_*ito 13

你不能没有另一个.

当你写:

using(MyClass myObj = new MyClass())
{
    myObj.SomeMthod(...);
}
Run Code Online (Sandbox Code Playgroud)

编译器将生成如下内容:

MyClass myObj = null;
try
{
    myObj = new MyClass();
    myObj.SomeMthod(...);
}
finally
{
    if(myObj != null)
    {
        ((IDisposable)myObj).Dispose();
    }
} 
Run Code Online (Sandbox Code Playgroud)

因此,当您有using关键字时可以看到,假设/要求实现IDisposable.


Joh*_*n K 12

如果使用该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
    }
}
Run Code Online (Sandbox Code Playgroud)

这使您能够:

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.
Run Code Online (Sandbox Code Playgroud)

实际上和写作一样:

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. 
}
Run Code Online (Sandbox Code Playgroud)

  • 实际上它是一个非常有用的模式,无论何时你有"三明治"代码必须/应该在最后一节执行一些东西.例如,一个常见的场景是繁忙的光标,步骤是...... 1. /复制现有的光标2. /将光标设置为等待光标3. /在最后一节复制回原始光标.使用using和IDisposable然后你可以编写类似于使用的代码(Busy.WaitCursor){//其中WaitCursor是一个静态属性,它返回一个Busty构造函数复制和设置以及dispose()重新设置的实例.} (2认同)

Ric*_*ein 5

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

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