溫馨提示×

如何在C#中使用構(gòu)造函數(shù)鏈

c#
小樊
82
2024-09-11 01:38:19
欄目: 編程語言

在C#中,構(gòu)造函數(shù)鏈?zhǔn)侵敢粋€構(gòu)造函數(shù)調(diào)用另一個構(gòu)造函數(shù)

public class MyClass
{
    private int a;
    private int b;

    // 默認(rèn)構(gòu)造函數(shù)
    public MyClass() : this(0, 0)
    {
        // 你可以在這里添加更多的初始化代碼
    }

    // 帶有兩個參數(shù)的構(gòu)造函數(shù)
    public MyClass(int a, int b)
    {
        this.a = a;
        this.b = b;
    }

    // 帶有一個參數(shù)的構(gòu)造函數(shù),通過調(diào)用帶有兩個參數(shù)的構(gòu)造函數(shù)來初始化
    public MyClass(int a) : this(a, 0)
    {
        // 你可以在這里添加更多的初始化代碼
    }
}

在這個例子中,我們定義了三個構(gòu)造函數(shù)。當(dāng)調(diào)用不帶參數(shù)的構(gòu)造函數(shù)時,它會調(diào)用帶有兩個參數(shù)的構(gòu)造函數(shù),將ab都設(shè)置為0。當(dāng)調(diào)用帶有一個參數(shù)的構(gòu)造函數(shù)時,它會調(diào)用帶有兩個參數(shù)的構(gòu)造函數(shù),將b設(shè)置為0,而a則根據(jù)傳入的參數(shù)值進行設(shè)置。這樣,我們可以通過構(gòu)造函數(shù)鏈簡化代碼并確保所有的構(gòu)造函數(shù)都能正確地初始化對象。

0