有什么用关键字和IDisposable接口之间的关系?什么用、接口、关键字、关系

2023-09-02 02:00:46 作者:杀手心未动

如果我使用使用关键字,我还是要落实的IDisposable

If I am using the using keyword, do I still have to implement IDisposable?

推荐答案

如果您使用的 使用语句的封闭式必须已经实施的 的IDisposable 否则编译器会发出错误。因此,考虑IDisposable的实现要使用的prerequisite。

If you use the using statement the enclosed type must already implement IDisposable otherwise the compiler will issue an error. So consider IDisposable implementation to be a prerequisite of using.

。然而,这是一种落后的这样做,因为没有意义,这样做是为了它的缘故。只有当你有事要处理的像一个非托管资源,你应该实现它。

If you want to use the using statement on your custom class, then you must implement IDisposable for it. However this is kind of backward to do because there's no sense to do so for the sake of it. Only if you have something to dispose of like an unmanaged resource should you implement it.

// 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.

有效的是一样的写法:

Effectively that's the same as writing:

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