How can I tell the inheriting class to not call its base class' parameter-less constructor?

前端 未结 7 2708
礼貌的吻别
礼貌的吻别 2021-02-19 23:32

I was surprised to find out that the parameter-less constructor of my base class is called any time I call any constructor in a derived class. I thought that is what

7条回答
  •  别跟我提以往
    2021-02-20 00:13

    When you instantiate a class all the classes in the inheritance hierarchy are instantiated starting from the topmost Parent to the lowermost child, stopping at the type you instantiated. So if you instantiate System.Text.StringBuilder(), first you call the default constructor of System.Object, then StringBuilder(). You can use the base keyword to call a different constructor (one with equal or fewer params), but not more params. If you do not specify base, the default constructor is called, thus the reason this is happening to you. You can also use the base keyword within the context of an instance method to call base implementations, such as in the case of the decorator pattern. If you do not want to call the base class private constructors then you should set the children with private default constructors and also explicitly call base(params) on your other constructors.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication2
    {
        class ProcessCaller
        {
            static void Main()
            {
                MyDerived md1 = new MyDerived(1);
                object o = new System.Text.StringBuilder();//This will implicitly instantiate the classes in the inheritance hierarchy:  object, then stringbuilder
            }
        }
    
    public class MyBase
    {
       int num;
    
       public MyBase() 
       {
          Console.WriteLine("in MyBase()");
       }
    
       public MyBase(int i )
       {
          num = i;
          Console.WriteLine("in MyBase(int i)");
       }
    
       public virtual int GetNum()
       {
          return num;
       }
    }
    
    public class MyDerived: MyBase
    {
       //set private constructor.  base(i) here makes no sense cause you have no params
       private MyDerived()
       {
    
       }
    
        // Without specifying base(i), this constructor would call MyBase.MyBase()
       public MyDerived(int i) : base(i)
       {
       }
       public override int GetNum()
       {
           return base.GetNum();//here we use base within an instance method to call the base class implementation.  
       }
    }
    
    }
    

提交回复
热议问题