Tro*_*roy 5 .net c# idisposable using-statement resource-management
如果我使用using
关键字,我还需要实现IDisposable
吗?
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)
你是混乱的事情.您只能在实现IDisposable的内容上使用"using"关键字.
编辑:如果使用using关键字,则不必明确调用Dispose,它将在using块的末尾自动调用.其他人已经发布了如何将using语句转换为try-finally语句的示例,并在finally块中调用Dispose.
归档时间: |
|
查看次数: |
2919 次 |
最近记录: |