C#中的析构函数 [英] Destructor in C#

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

问题描述

Finalize()是C#中的析构函数,并且由GC使用.

Finalize() is a destructor in C# and it is used by the GC.
Is there anyway we can use it when we want to free the memory space?

推荐答案

看看这里有什么好的参考资料:

正确实施IDisposable和处置模式 [对IDisposable的另一种观察 [ http://www.devx.com/dotnet/Article/33167 [
Have a look here for some good reference:

Implementing IDisposable and the Dispose Pattern Properly[^]

Another Look At IDisposable[^]

http://www.devx.com/dotnet/Article/33167[^]

Good luck!


不能直接调用析构函数/终结器.当没有对对象的引用且垃圾收集器(GC)运行时,将自动调用它.

如果要释放资源,则应实现实现IDisposable的处置模式(如下所示),则类的使用者有两种选择:
1.完成后调用Dispose()
2.使用using块,它将被自动调用
A destructor/finalizer cannot be called directly. It is called automatically when no references to the object remain AND the Garbage Collector (GC) runs.

If you want to free resources you should implement the dispose pattern implementing IDisposable (as below) then consumers of your class have two choices:
1. Call Dispose() when they''re done
2. Use a using block and it will be called automatically
public class YourClass : IDisposable
{
    private bool isDisposed;

    ~YourClass()
    {
        Dispose(false);
    }

    public bool IsDisposed
    {
        get{ return isDisposed; }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SupressFinalize(this);
    }
    protected virtual void Dispose(bool disposing)
    {
        if(!isDisposed)
        {
            if(disposing)
            {
                // dispose managed resources here
            }
            // dispose unmanaged resources here
            isDisposed = true;
        }
    }
}




Google一直是我们的朋友.首先是Google it Man!.对于您在Google中的问题标题,我获得了76,200个结果.
C#中的析构函数 [ ^ ]

这些结果之一,单击此处 [
Hi,

Google is always our friend. First Google it Man!. For your question title in google i got 76,200 results. Destructor in C#[^]

One of those results, Click Here[^]


这篇关于C#中的析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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