C#構造函數中:this()的做用

       通俗來講,能夠說是構造函數的繼承函數

       (1) :this()用來繼承無參時的構造函數,例以下面代碼this

    static void Main(string[] args)
        {
            AA aA = new AA("c","d");
            Console.WriteLine(aA.aa);
            Console.WriteLine(aA.bb);
            Console.WriteLine(aA.cc);
            Console.WriteLine(aA.dd);
            Console.WriteLine(aA.ee);

            Console.ReadKey();
        }
    }
    class AA
    {
      public  string aa="aa 未初始化";
      public  string bb= "bb 未初始化";
      public  string cc= "cc未初始化";
      public  string dd= "dd 未初始化";
      public  string ee= "ee 未初始化";
        public AA(string c,string d):this()
        {
            this.cc = c;
            this.dd = d;
        }
        public AA()
        {
            this.aa = "a";
            this.bb = "b";
        }
    }

       類AA的構造過程爲,先構造無參的AA(),而後再對應參數的構造函數,顯示結果爲spa

           

 

       (2)  :this(para)3d

       若是咱們要繼承有參的構造函數,則須要構造函數簽名的時候就初始化code

       以下面代碼blog

 class Program
    {
        static void Main(string[] args)
        {
            AA aA = new AA("c","d");
            Console.WriteLine(aA.aa);
            Console.WriteLine(aA.bb);
            Console.WriteLine(aA.cc);
            Console.WriteLine(aA.dd);
            Console.WriteLine(aA.ee);

            Console.ReadKey();
        }
    }
    class AA
    {
      public  string aa="aa 未初始化";
      public  string bb= "bb 未初始化";
      public  string cc= "cc未初始化";
      public  string dd= "dd 未初始化";
      public  string ee= "ee 未初始化";
        public AA(string c,string d):this("e")  //此處初始化了一個參數
        {
            this.cc = c;
            this.dd = d;
        }
        public AA()
        {
            this.aa = "a";
            this.bb = "b";
        }
        //此處是新的帶一個參數的構造函數
        public AA(string e)
        {
            this.ee = e;
        }
    }

        此代碼會優先構造AA(string e)的構造函數,而後繼續構造對應的構造函數繼承

        運行結果爲string

        

相關文章
相關標籤/搜索