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