如何为我的类实现IDisposable接口,以便可以在'using'块中使用?

3

我正在使用C#编程,并创建了一个类,希望在“using”块中使用。

这是否可行?如果是,我该如何进行,还需要添加什么到我的类中?


2
公共类Email:IDisposable,然后实现Dispose,在Dispose内清理您的资源。 - Dave Zych
4
虽然@DaveZych的实现是正确的,但你应该先问自己一个问题:我为什么要这样做?除非你确实需要清理可能会变成孤立或锁定的资源,否则这只是一种不必要的表面应用。除非你真正需要管理资源,否则去修改IDisposable是个坏主意。 - Joel Etherton
你可以在任何实现了 IDisposable 接口的类上使用 using 关键字,这意味着只需要实现 Dispose() 方法即可。正确地实现这一点是相当棘手的,并且仅在你的类持有大型和/或非托管资源时才有益处。 - Honza Brestan
2个回答

4
using关键字可以用在任何实现了IDisposable接口的对象上。要实现IDisposable接口,需要在类中包含一个Dispose方法。
通常也很重要在类的finalizer中包括Dispose功能,以防库的用户没有调用(或忘记调用)Dispose
例如:
class Email : IDisposable {

    // The only method defined for the 'IDisposable' contract is 'Dispose'.
    public void Dispose() {
        // The 'Dispose' method should clean up any unmanaged resources
        // that your class uses.
    }

    ~Email() {
        // You should also clean up unmanaged resources here, in the finalizer,
        // in case users of your library don't call 'Dispose'.
    }
}

void Main() {

    // The 'using' block can be used with instances of any class that implements
    // 'IDisposable'.
    using (var email = new Email()) {

    }
}

1
根据实际问题(标题),我认为OP已经拥有这些信息。 - Joel Etherton

0
public class MyClass : IDisposable
{
    public void Dispose()
    {
    }
}

就是这样!在调用代码中,您可以执行以下操作:

using(var mc = new MyClass())
{
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接