我正在使用C#编程,并创建了一个类,希望在“using”块中使用。
这是否可行?如果是,我该如何进行,还需要添加什么到我的类中?
我正在使用C#编程,并创建了一个类,希望在“using”块中使用。
这是否可行?如果是,我该如何进行,还需要添加什么到我的类中?
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()) {
}
}
public class MyClass : IDisposable
{
public void Dispose()
{
}
}
就是这样!在调用代码中,您可以执行以下操作:
using(var mc = new MyClass())
{
}
IDisposable
接口的类上使用using
关键字,这意味着只需要实现Dispose()
方法即可。正确地实现这一点是相当棘手的,并且仅在你的类持有大型和/或非托管资源时才有益处。 - Honza Brestan