建構函式就是類別的「方法」,主要對物件進行初始化設定,當對類別進行「實體化(new)」成為物件時,便會自動執行建構函式。
1.建構函式名稱與類別名稱相同
2.當對類別透過new進行實體化成為物件時,會自動執行建構函式的敘述。
3.建構函式可以多載(overloading)
解構函式也是類別的「方法」,主要是釋放該物件所配置的資源,當物件被Dispose或Close時,便會自動執行解構函式。
1.建構函式名稱與類別名稱相同,但須於解構函式前面加一個「~」
2.解構函式只能一個
3.解構函式會自動被叫用,不能直接被呼叫

namespace Constructor_Destructor_ex
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btn_Construct1_Click(object sender, EventArgs e)
        {
            Student Std1 = new Student(); //執行無參數的建構函數
            MessageBox.Show(this, Std1.ToString(), "無參數建構函數");
        }

        private void btn_Construct2_Click(object sender, EventArgs e)
        {
            Student Std2 = new Student(180,600); //執行有參數的建構函數
            MessageBox.Show(this, Std2.ToString(), "有參數建構函數");
        }

        private void btn_close_Click(object sender, EventArgs e)
        {
            Student Std = new Student();
            this.Close(); //會去呼叫解構函數
        }
    }
}

class Student
{
    public int IQ;//智商
    public int EnrollScore;//入學成績
    public string ClassResult;//分配班級結果

    public Student() //建構函數
    {
        IQ = 100;
        EnrollScore = 0;
    }

    public Student(int NewIQ, int NewEnrollScore) //多載建構函數
    {
        this.IQ = NewIQ;
        this.EnrollScore = NewEnrollScore;
    }

    //重寫類別Student的ToString()方法
    public override string ToString()
    {
        if (IQ > 150 && EnrollScore > 500)
        {
            ClassResult = "資優班";
        }
        else
        {
            ClassResult = "普通班";
        }
        return ClassResult;
    }

    ~Student() //解構函數
    {
        MessageBox.Show("呼叫解構函式Studnet物件資源釋放中...");
    }

}

arrow
arrow
    全站熱搜

    羅 朝淇 發表在 痞客邦 留言(0) 人氣()