1. 程式人生 > >C#基礎(一)--建構函式

C#基礎(一)--建構函式

建構函式:

     主要是用來建立物件時為物件進行初始化賦值。總與new運算子一起使用在建立物件時。

     建構函式的名稱和類名一樣,一個類可以擁有多個建構函式。

    建構函式在例項化類時,最先執行。

    建構函式沒有返回值,也不能用void修飾符,只有訪問修飾符。

    每個類中都會一個建構函式,如果使用者定義的類中沒有顯式的定義任何建構函式,編譯器就會自動為該型別生成預設建構函式,類裡面沒有建構函式也可以,系統會為你自動建立無參建構函式。

程式碼:

    

 public class ColorHelper
    {
        string Yellow;
        string Red;
        public ColorHelper();

        public ColorHelper(string yellow)
        {
            this.Yellow = yellow;
        }

        public ColorHelper(string yellow, string red)
        {
            this.Red = red;
            this.Yellow = yellow;
        }

        public static void Invoking() //呼叫
        {
            ColorHelper aa = new ColorHelper();
            ColorHelper bb = new ColorHelper("Yellow");
            ColorHelper cc = new ColorHelper("Yellow", "Red");
        }

    }