溫馨提示×

c#中構(gòu)造函數(shù)能否調(diào)用其他構(gòu)造函數(shù)

c#
小樊
81
2024-09-23 17:42:35
欄目: 編程語言

是的,在C#中,一個構(gòu)造函數(shù)可以調(diào)用另一個構(gòu)造函數(shù)。為了實現(xiàn)這一點,您需要使用this關(guān)鍵字。this關(guān)鍵字表示對當前對象的引用。以下是一個示例:

public class MyClass
{
    private int x;
    private int y;

    // 第一個構(gòu)造函數(shù)
    public MyClass()
    {
        this(0, 0); // 調(diào)用第二個構(gòu)造函數(shù)
    }

    // 第二個構(gòu)造函數(shù)
    public MyClass(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

在這個例子中,我們有兩個構(gòu)造函數(shù)。第一個構(gòu)造函數(shù)不接受任何參數(shù),它將調(diào)用第二個構(gòu)造函數(shù)并傳遞默認值(0,0)。第二個構(gòu)造函數(shù)接受兩個參數(shù),并將它們分別賦值給類的屬性。

0