none
如何才能使子类和父类的非默认构造函数和默认构造函数都执行一次? RRS feed

  • 问题

  • 例如:
    public class MyBaseClass
    {
        public MyBaseClass()
        {
        }
        public MyBaseClass(int i)
        {
        }
    }
    public class MyDerivedClass : MyBaseClass
    {
        public MyDerivedClass()
        {
        }
        public MyDerivedClass(int i)
        {
        }
    }
    new MyDerivedClass(1)的执行顺序是:MyBaseClass() -> MyDerivedClass(1)
    MyBaseClass(1)和MyDerivedClass()没有被执行
    如改为:
    public class MyBaseClass
    {
        public MyBaseClass()
        {
        }
        public MyBaseClass(int i)
        {
        }
    }
    public class MyDerivedClass : MyBaseClass
    {
        public MyDerivedClass()
        {
        }
        public MyDerivedClass(int i) : base(i)
        {
        }
    }
    new MyDerivedClass(1)的执行顺序是:MyBaseClass(1) -> MyDerivedClass(1)
    MyBaseClass()和MyDerivedClass()没有被执行

    改为:
    public class MyBaseClass
    {
        public MyBaseClass()
        {
        }
        public MyBaseClass(int i) : this()
        {
        }
    }
    public class MyDerivedClass : MyBaseClass
    {
        public MyDerivedClass()
        {
        }
        public MyDerivedClass(int i) : base(i)
        {
        }
    }
    new MyDerivedClass(1)的执行顺序是:MyBaseClass() -> MyBaseClass(1) -> MyDerivedClass(1)
    MyDerivedClass()没有被执行

    改为:
    public class MyBaseClass
    {
         public MyBaseClass()
        {
        }
        public MyBaseClass(int i)
        {
        }
    }
    public class MyDerivedClass : MyBaseClass
    {
        public MyDerivedClass()
        {
        }
        public MyDerivedClass(int i) : this()
        {
        }
    }
    new MyDerivedClass(1)的执行顺序是:MyBaseClass() -> MyDerivedClass() -> MyDerivedClass(1)
    MyBaseClass(1)没有被执行
    如何定义,才能是MyBaseClass(),MyBaseClass(1),MyDerivedClass(),MyDerivedClass(1)都能被执行一次?
    2017年1月19日 8:27

全部回复

  •     public class MyBaseClass
        {
            public MyBaseClass()
            {
                Console.WriteLine("{0}", "MyBaseClass");
            }
            public MyBaseClass(int i) : this()
            {
                Console.WriteLine("{0}{1}", "MyBaseClass", i);
            }
        }
        public class MyDerivedClass : MyBaseClass
        {
            static private int I { get; set; }
            public MyDerivedClass() : base(I)
            {
                Console.WriteLine("{0}", "MyDerivedClass");
            }
            public MyDerivedClass(int i) : this(I = i, false)
            {
                Console.WriteLine("{0}{1}", "MyDerivedClass", i);
            }
            private MyDerivedClass(int i, bool b) : this()
            {
                Console.WriteLine("{0}{1}{2}", "MyDerivedClass", i, b);
            }
        }

    输出顺序:

    MyBaseClass
    MyBaseClass1
    MyDerivedClass
    MyDerivedClass1False
    MyDerivedClass1

    2017年1月25日 3:42