簡體   English   中英

我可以在C#中調用同一個類的重載構造函數嗎?

[英]Can I call a overloaded constructor of the same class in C#?

我知道我可以用':this()'來做到這一點,但如果我這樣做,重載的構造函數將首先被執行,我需要它在將調用它的構造函數之后執行。 很難解釋讓我把一些代碼:

Class foo{
    public foo(){
       Console.WriteLine("A");
    }
    public foo(string x) : this(){
       Console.WriteLine(x);
    }
}

/// ....

Class main{
    public static void main( string [] args ){
       foo f = new foo("the letter is: ");
    }
}

在此示例中,程序將顯示

A 
the letter is:

但我想要的是

the letter is: 
A

有一種'優雅的方式'來做到這一點? 我寧願避免將構造函數提取到分離方法並從那里調用它們。

是的,你可以很容易地做到這一點(不幸的是):

class foo {
    public foo( ) {
        Console.WriteLine( "A" );
    }
    public foo( string x ) {
        Console.WriteLine( x );

        var c = this.GetType( ).GetConstructor( new Type[ ] { } );
        c.Invoke( new object[ ] { } );
    }
}

class Program {
    static void Main( string[ ] args ) {
        new foo( "the letter is: " );
    }
}

將構造函數操作提取到虛擬方法並從那里調用它們。

這使您可以完全控制派生類的功能相對於基類運行的順序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM