3

我知道我可以用':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

有一种“优雅的方式”可以做到这一点吗?我宁愿避免将构造函数操作提取到分离的方法并从那里调用它们。

4

2 回答 2

2

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

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: " );
    }
}
于 2014-02-17T20:21:41.797 回答
0

将构造函数操作提取到虚拟方法并从那里调用它们。

这使您可以完全控制派生类的功能相对于基类运行的顺序。

于 2014-02-17T19:20:24.657 回答