使用C#析构函数的示例 [英] Sample use of a C# Destructor

查看:144
本文介绍了使用C#析构函数的示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读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屋!

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