繁体   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