C#學習筆記005-建構函式
阿新 • • 發佈:2019-02-19
public class Student { private string name; public string Name { get { return name; } set { name = value; } } private int age; public int Age { get { return age; } set { age = value; } } private char sex; public char Sex { get { return sex; } set { sex = value; } } private string food; public string Food { get { return food; } set { food = value; } } public Student(int age, char sex, string food, string name) { this.Name = name; this.Age = age; this.Sex = sex; this.Food = food; } //重寫了建構函式,讓一開始就可以初始化 public Student(string name, int age, char sex) { //都是賦值給屬性,屬性才能對欄位做限制 this.Name = name; this.Age = age; this.Sex = sex; } //過載建構函式 //只要引數不一樣就可以過載,包括型別和引數數量不一樣都可以 //這裡呼叫了4個引數的 public Student(string name, int age, char sex,string food) //用:this可以呼叫建構函式,但是需要給呼叫的函式的每個引數賦值 //age,sex,name都由該建構函式public Student(int age, char sex, string name)傳入 //food則需要我們賦值,當然賦值之後也用不上 public Student(int age, char sex, string name) : this(age, sex, " ", name) { } //解構函式,無論寫在哪裡,都是在程式結束的時候才呼叫 //解構函式一般都不用我們手動呼叫 ~Student() { } //一個介紹自己的函式 public void Say() { Console.WriteLine("我是{0},年齡{1}歲,性別{2}", this.Name, this.Age, this.Sex); } } class Program { static void Main(string[] args) { Student liSi = new Student("李四", 18, '男'); Student zhangSan = new Student(19, '女', "張三"); zhangSan.Say(); liSi.Say(); Console.ReadKey(); } }
總結:
1、不寫建構函式會有一個預設無引數的建構函式,沒有返回值,也不能寫void
2、重寫的建構函式也沒有返回值,也不能寫void,但是可以在宣告物件的時候例項化
3、:this可以呼叫該類的建構函式,減少重寫建構函式時的冗餘程式碼
4、解構函式一般不呼叫,因為C#有garbage collection,會自己釋放資源。除非需要馬上釋放資源,我們可以去手動呼叫