使用C#析构函数的示例 [英] Sample use of a C# Destructor
问题描述
我正在阅读C#中的析构函数,但是我很难找到一个体面的用例。
有人可以提供一个使用示例解释?
非常感谢。
$ b
更新
本书中的代码示例实现了Desctuctor和Dispose()方法,请参阅本书中的这段代码片段。
class MyClass
{
bool disposed = false; //处置状态
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
〜MyClass()
{
Dispose(false);
protected void Dispose(bool disposing)
{
if(dispose == false)
{
if(disposing == true)
{
//处理托管资源。 Factored Dispose
}
//处理非托管资源。
}
disposed = true;
Marko
SafeHandle
。 Joe Duffy有一个<一个很好的帖子关于这个,它比我更详细能写自己 - 所以去阅读:)
关于术语的简要说明:ECMA版本的C#规范将它们称为终结器;微软版本的规范一直将它们称为析构函数,并继续这样做。
I'm reading about destructors in C# but I'm having trouble finding a decent use-case for it.
Could someone provide an example of usage with an explanation?
Much, much appreciated.
Update
The code sample in the book implements both a Desctuctor and a Dispose() method, see this code snippet from the book.
class MyClass
{
bool disposed = false; // Disposal status
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~MyClass()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (disposed == false)
{
if (disposing == true)
{
// Dispose the managed resources. Factored Dispose
}
// Dispose the unmanaged resources.
}
disposed = true;
}
}
Marko
Finalizers are very rarely needed now. They used to be required when you had direct access to native resources - but now you should usually be using SafeHandle
instead.
Joe Duffy has an excellent post about this which goes into rather more details than I would be able to write myself - so go read it :)
A quick note on terminology: the ECMA version of the C# spec refers to them as finalizers; the Microsoft version of the spec has always referred to them as destructors and continues to do so.
这篇关于使用C#析构函数的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!