我的类有相当一些属性,我的一个构造函数将它们全部设置,我希望默认构造函数调用另一个构造函数并使用set属性。但是我需要首先准备参数,所以从标题中调用它无助于你。如何在其他构造函数中调用构造函数?
这是我想做什么:
public class Test
{
private int result, other;
// The other constructor can be called from header,
// but then the argument cannot be prepared.
public Test() : this(0)
{
// Prepare arguments.
int calculations = 1;
// Call constructor with argument.
this(calculations);
// Do some other stuff.
other = 2;
}
public Test(int number)
{
// Assign inner variables.
result = number;
}
}
所以这是不可能的,没有人知道该怎么称呼我的构造函数来设置内部代码参数?目前我从另一个构造函数存储对象的副本并复制所有的属性,这真的很烦人。
不要想着把preperation放在一个单独的方法,它不是理想的,但它会工作,谢谢。 – MrFox 2010-11-14 22:28:46
并且取决于它的复杂程度,它也可以在this()内部表达。()cpnstruction – 2010-11-14 22:33:18
只是一个小提示:第二种方法中'PrepareArgument'必须是'static'。 – 2015-01-28 10:14:06