构造函数及析构函数

构造函数及析构函数是一组特殊的成员函数,用来对对象进行初始化以及回收,这两个都是与实例对象挂钩的。
当该类被实例对象化时,构造函数就会自动运行,对象的初始化过程也就自动完成,但是当我们想要按照自己所需要的初始化时,比如我们想要初始化对象的数据,就需要用到构造函数了。
当该类结束时,就会自动进行析构函数,可以说实例对象是以构造函数开始,以析构函数为结束。
构造函数的定义规范是具有与该类相同的名称,例如程序:

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()就自动调用了,可以把构造函数理解为对类对象的一个初始化过程。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace STRUC
{
    class Program
    {
        static void Main(string[] args)
        {
            GouZAO gouzao = new GouZAO(1,2,3);
            //初始化对象时,可以直接赋值;
            
        }
    }
    class GouZAO
    {
      public  int a ;
       public int b ;
      public  int c ;
        public int d;
       public GouZAO(int x,int y,int z)
        {
            this.a = x;
            //this 后面的a指的就是类中的数据变量;
            this.b = y;
            this.c = z;
            Cal();
        }
        public void Cal()
        {

            d = a + b + c;
            Console.WriteLine("运行结果是:{0}",d);
        } 

    }
}

这里就是在构造函数中初始化所需要的值。

而析构函数则是在实例对象失效后,就自动进行函数执行,可以用来进行垃圾回收,其书写格式与构造函数类型相似,例如程序:

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("这是析构函数");
        }

    }
}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值