C# 建構子呼叫

父類別 & 子類別 建構子呼叫順序

//父類別 (抽象)
abstract class Shape
    {
        //沒有無參數建構子
        //public Shape() { Console.WriteLine("Shape()"); }
        
        //有參數建構子(有預設值)
        public Shape(string name = "NoName")
        {
            Console.WriteLine("Shape(name)");
            PetName = name;
        }
        
        //有參數建構子(只有一個有預設值)
        public Shape(string name,int num = 0)
        {
            Console.WriteLine("Shape(name,num)");
        }
        public string PetName { get; set; }

        //表示可被子類 override
        public virtual void Draw()
        {
            Console.WriteLine("Inside Shape.Draw()");
        }
    }

//子類別 繼承 Shape
    class Circle : Shape
    {
        public Circle() { Console.WriteLine("Circle()"); }

        public Circle(string name) : base(name) { Console.WriteLine("Circle(name)"); }

        public override void Draw()
        {
            Console.WriteLine("Drawing {0} the Circle", PetName);
        }
    }

根據以上程式 當呼叫 Circle circle = new Circle(); 

s1. public Shape(){...}  //預設呼叫父類別ㄨ

s2. public Circle(){...}

*問題:子類別 若不明確呼叫建構子 (例如: public Circle():base("Cir"){...})

此時父類別若無明確宣告 無參數建構子 (public Shape(){...}),則會產生錯誤

原因:(因為父類別有定義其他建構子,public Shape(string name,int num=1){...})

解決方式:

1.初始化建構子所有參數值(public Shape(string name = "NoName"){...})

2.明確建立父類別無參數建構子(public Shape(){...})

3.子類別明確呼叫父類別建構子(public Circle():base("Cir"){...})