C#构造函数与析构函数--C#基础
1.构造函数
1)构造函数没有返回值,也不能写void,必须是public 修饰符
2)构造函数和类名相同
3)构造函数也是可以重载的
public Clerk(string name,Gender gender,int age,string deparment)
{
this.Name = name;
this.Gender = gender;
this.Age = age;
this.Department = deparment;
}
public Clerk(string name,Gender gender,int age) {
this.Name = name;
this.Gender = gender;
this.Age = age;
}
//构造函数也是可以重载的
5)类当中会有一个默认的无参数构造函数,当写新的的构造函数之后,不管是有参数还是没有,那个默认的构造函数都会被覆盖掉
Program.cs(Add)
Clerk c3=new Clerk();//以这种方式去实例化类时,就需要把无参函数补回
Clerk.cs:(Add)
public Clerk()
{
}
6)关于new关键字
在内存中开辟空间
在开辟空间中创建对象
对对象进行初始化,将各个属性进行赋值
7)构造函数举例:
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 构造函数析构函数
{
class Program
{
static void Main(string[] args)
{
//不会有c1._name只会有c1.
Clerk c1=new Clerk("张三",Gender.男,23,"人力资源");
c1.Write();
Clerk c2= new Clerk("李四",Gender.男,30);
c2.Write2();
Console.ReadKey();
}
}
}
Clerk.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 构造函数析构函数
{
public enum Gender
{
男,女
}
class Clerk
{
private string _name;
public string Name
{
get{return _name;}
set{_name = value;}
}
private Gender _gender;
public Gender Gender
{
get { return _gender; }
set { _gender = value; }
}
private string _department;
public string Department
{
get { return _department; }
set { _department = value; }
}
private int age;//默认是0
public int Age
{
get { return age; }
set { age = value; }
}
public void Write() {
Console.WriteLine("我是{0},{1},{2}岁了,在{3}任职",this.Name,this.Gender,this.Age,this.Department);
}
public void Write2()
{
Console.WriteLine("我是{0},{1},{2}岁了", this.Name, this.Gender, this.Age);
}
public Clerk(string name,Gender gender,int age,string deparment)
{
this.Name = name;
this.Gender = gender;
this.Age = age;
this.Department = deparment;
}
public Clerk(string name,Gender gender,int age) {
this.Name = name;
this.Gender = gender;
this.Age = age;
}
}
}
2.析构函数
1)析构函数是实现销毁一个类的实例的方法成员
2)析构函数不能有参数、不能有任何修饰符而且不能被调用
3)与构造函数写法同,但在前面加“~”,也没有public
4)如果系统中没有指定析构函数,那么编译器由GC(Garbage Collection垃圾回收)来决定什么时候进行释放资源如果想立即执行回收可以在程序上加上,在使用完当前类时会被调用
~Clerk() {
Console.WriteLine("我是析构函数");
}