如果我使用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();
}
编辑:一个有用的例子。
当您发现自己在finally部分做一些事情时,例如将光标重置回默认值,而在设置为等待光标后,这是该模式的候选人...
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.
}
using 关键字已经实现,所以如果你使用 using 关键字,你就不需要调用 IDisposable
error CS1674: 'SomeType': type used in a using statement must be implicitly convertible to 'System.IDisposable'
using
语句的控制变量必须是实现了IDisposable
接口的类型。然而,某些方法包含using
语句并不意味着包含这些方法的类必须实现IDisposable
接口。类实现IDisposable
接口最常见的原因是它们包含的资源的生命周期无法在using
语句中封装。 - supercat