C#构造函数中:this()的作用

       通俗来说,可以说是构造函数的继承

       (1) :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(),然后再对应参数的构造函数,显示结果为

           

 

       (2)  :this(para)

       如果我们要继承有参的构造函数,则需要构造函数签名的时候就初始化

       如下面代码

 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)的构造函数,然后继续构造对应的构造函数

        运行结果为

        

posted on 2018-02-05 16:48  鲁广广  阅读(8611)  评论(0编辑  收藏  举报

导航