有什么用关键字和IDisposable接口之间的关系? [英] What is the relationship between the using keyword and the IDisposable interface?

查看:140
本文介绍了有什么用关键字和IDisposable接口之间的关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用使用关键字,我还是要落实的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. 
}

这篇关于有什么用关键字和IDisposable接口之间的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆