我知道我可以使用':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: " );
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句