构造函数及析构函数

构造函数及析构函数是一组特殊的成员函数,用来对对象进行初始化以及回收,这两个都是与实例对象挂钩的,当该类被实例对象化时,构造函数就会自动运行,当该类结束时,就会自动进行析构函数,可以说实例对象是以构造函数开始,以析构函数为结束。
构造函数的定义规范是具有与该类相同的名称,例如程序:

namespace STRUC
{
    class Program
    {
        static void Main(string[] args)
        {
            GouZAO gouzao = new GouZAO();
            Console.WriteLine("构造函数的结果是:{0}",gouzao.c);
        }
    }
    class GouZAO
    {
      public  int a =2;
       public int b = 1;
      public  int c ;
        public  GouZAO()
        {
            c = a + b;
        }

    }
}

结果是:
在这里插入图片描述
可以发现当class GouZAO类被实例化之后,构造函数public GouZAO()就自动调用了,可以把构造函数理解为对类对象的一个初始化过程。
而析构函数则是在实例对象失效后,就自动进行函数执行,可以用来进行垃圾回收,其书写格式与构造函数类型相似,例如程序:

namespace STRUC
{
    class Program
    {
        static void Main(string[] args)
        {
            GouZAO gouzao = new GouZAO();
            
        }
    }
    class GouZAO
    {
      public  int a =2;
       public int b = 1;
      public  int c=2 ;
       ~GouZAO()
        {
            Console.WriteLine("这是析构函数");
        }

    }
}

结果是:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/DOUBLE121PIG/article/details/84643251