首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 建構函式參數:無參數 vs 參數化、車輛繼承實例驗證、base 傳遞與多載解析

     編輯:關於C語言

建構函式參數 讓實例化時傳遞初始化資料,支援多載提供不同初始化路徑。

無參數 vs 參數化

  • 無參數:固定初始化。
  • 參數化:呼叫端必須提供引數,否則該建構函式不被選中。

車輛繼承完整驗證


class Vehicle {
    public int Wheels; protected float Weight;
    public Vehicle() {}
    public Vehicle(int w, float g) { Wheels=w; Weight=g; }
    public void Show() => Console.WriteLine($"W:{Wheels} Wt:{Weight}");
}

class Train {
    public int Num; private int Passengers; private float Weight;
    public Train() {}
    public Train(int n, int p, float w) { Num=n; Passengers=p; Weight=w; }
    public void Show() => Console.WriteLine($"N:{Num} Wt:{Weight} P:{Passengers}");
}

class Car : Vehicle {
    int Passengers;
    public Car(int w, float g, int p) : base(w,g) { Passengers=p; }
    public new void Show() => Console.WriteLine($"W:{Wheels} Wt:{Weight} P:{Passengers}");
}

class Test {
    static void Main() {
        Vehicle v1 = new Vehicle(4,5);
        Train t1 = new Train();
        Train t2 = new Train(10,100,100);
        Car c1 = new Car(4,2,4);
        v1.Show(); t1.Show(); t2.Show(); c1.Show();
    }
}

輸出結果

W:4 Wt:5
N:0 Wt:0 P:0
N:10 Wt:100 P:100
W:4 Wt:2 P:4

關鍵觀察

  • Car 以 : base(w,g) 明確呼叫基類建構函式。
  • new void Show() 隱藏基類 Show(非覆寫)。
  • 無參數建構函式保留預設值(0/null)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved