3

我正在用 C# 编写代码,并创建了一个我想在“使用”块中使用的类。

这可能吗?如果可以,我应该如何进行以及我需要在课堂上添加什么?

4

2 回答 2

4

using关键字可用于任何实现IDisposable. 要实现IDisposable,请在您的类中包含一个Dispose方法。

如果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()) {

    }
}
于 2012-11-26T18:00:53.680 回答
0
public class MyClass : IDisposable
{
    public void Dispose()
    {
    }
}

这里的所有都是它的!在调用代码时,您可以执行以下操作:

using(var mc = new MyClass())
{
}
于 2012-11-26T18:02:40.373 回答