zoukankan      html  css  js  c++  java
  • 【C#复习总结】析构函数

    上篇提到析构函数,就顺便复习一下。

     一 C# 析构函数

    1.1 析构函数的定义

    • 析构函数用于释放被占用的系统资源。
    • 析构函数的名字由符号“~”加类名组成。

    1.2 析构函数注意的问题

    • 使用析构函数时,应该注意下面的问题:
    • 只能在类中使用析构函数,不能在结构中使用析构函数。
    • 一个类只能有一个析构函数。
    • 不能继承或重载析构函数。
    • 析构函数只能被自动调用。
    • 析构函数没有任何修饰符、没有任何参数、也不返回任何值。

    1.3 调用析构函数

    • 垃圾回收器决定了析构函数的调用,我们无法控制何时调用析构函数。
    • 垃圾回收器检查是否存在应用程序不再使用的对象。如果垃圾回收器认为某个对象符合析构,则调用析构函数(如果有)并回收用来存储此对象的内存。
    • 程序退出时会调用析构函数。
    • 我们可以通过调用Collect强制进行垃圾回收,但是请不要这样做,因为这样做可能导致性能问题。

    二 构造函数与析构函数的区别

    • 构造函数和析构函数是在类中说明的两种特殊的成员函数。
    • 构造函数是在创建对象时,使用给定的值将对象初始化。
    • 析构函数用于释放一个对象。在对象删除前,使用析构函数做一些清理工作,它与构造函数的功能正好相反。

    三 示例

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
     
    namespace Test
    {
        class Program
        {
            class First                     // 基类First
            {
                ~First()                    // 析构函数
                {
                    Console.WriteLine("~First()析构函数");
                }
            }
            class Second : First            // Second类从First类派生
            {
                ~Second()                   // 析构函数
                {
                    Console.WriteLine("~Second()析构函数");
                }
            }
            class Third : Second            // Third类从Second类派生
            {
                ~Third()                    // 析构函数
                {
                    Console.WriteLine("~Third()析构函数");
                }
            }
            static void Main(string[] args)
            {
                // C#析构函数-www.baike369.com
                Third Third1 = new Third(); // 创建类的实例
            }
        }
    }

    程序运行时,这三个类的析构函数将自动被调用,调用顺序是按照从派生程度最大的(~Third())到派生程度最小的(~First())次序调用的,和构造函数的调用顺序正好相反。

    运行结果:

    ~Third()析构函数
    ~Second()析构函数
    ~First()析构函数
  • 相关阅读:
    lintcode:最大子正方形
    lintcode 中等题:k Sum ii k数和 II
    lintcode 中等题:A + B Problem A + B 问题
    Protege汉字不能正常显示问题
    Protege A DOT error has occurred错误
    lintcode :reverse integer 颠倒整数
    Reported time is too far out of sync with master. Time difference of 52692ms > max allowed of 30000ms
    Please add or free up more resources then turn off safe mode manually.
    Permission denied: user=root, access=WRITE, inode="/":hadoopuser:supergroup:drwxr-xr-x
    Hadoop重新格式化HDFS的方法
  • 原文地址:https://www.cnblogs.com/mhq-martin/p/9234320.html
Copyright © 2011-2022 走看看