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

        

相关文章
相关标签/搜索