简体   繁体   中英

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

I know that I can do that with ': this()' but if I do that the overloaded constructor will be excecuted first and I need it to be executed after the the constructor that will call it . . . . Is complicated to explain let me put some code:

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: ");
    }
}

In this example the program will show

A 
the letter is:

but what I want is

the letter is: 
A

There is a 'elegant way' to do this? I would prefer to avoid extracting the constructor actions to separated method and call them from there.

Yes, you can do this pretty easily (unfortunately):

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: " );
    }
}

Extract the constructor actions to virtual methods and call them from there.

This gives you complete control over the order in which the derived class's functionality runs relative to the base class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM