如何在其他构造函数中调用构造函数?

我的类有很多属性,我的一个构造函数将它们全部设置好,我希望默认构造函数调用另一个属性并使用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; } } 

所以这是不可能的,有没有人知道如何调用我的构造函数来设置代码内的参数? 目前我正在从其他构造函数存储对象的副本并复制所有属性,这真的很烦人。

是。 只需在第一次调用中传递值1即可

 public class Test { private int result, other; public Test() : this(1) { // Do some other stuff. other = 2; } public Test(int number) { // Assign inner variables. result = number; } 

}

你为什么不准备这个论点?

 public class Test { private int result, other; public Test() : this(PrepareArgument()) { // Do some other stuff. other = 2; } public Test(int number) { // Assign inner variables. result = number; } private int PrepareArgument() { int argument; // whatever you want to do to prepare the argument return argument; } } 

或者…如果要从默认构造函数中调用prepareArgument,那么它不能依赖于任何传入的参数。 如果它是一个常数,那就让它成为常数……

 public class Test { const int result = 1; private int result, other; public Test() { // Do some other stuff. other = 2; } } 

如果它的值依赖于其他外部状态,那么你可能会重新考虑你的设计……为什么不在首先调用构造函数之前计算它呢?

听起来像一点点重构会有所帮助。 虽然你不能完全按照自己的意愿去做,但总会有其他选择。 我意识到你的实际代码可能比你给出的代码更复杂,所以请以此为例来重构你的问题。 将所有公共代码提取到新的SetVariables方法中。

 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. SetVariables(calculations); // Do some other stuff. other = 2; } public Test(int number) { // Assign inner variables. SetVariables(number); } private void SetVariables(int number) { result = number; } } 

如果要调用构造函数,但不能从头文件中执行,唯一的方法是定义私有的Initialize方法。 看来你在构造函数中做了“真正的工作”,这不是构造函数的任务。 您应该考虑以不同的方式来实现您的目标,因为您严格禁止调试和其他人阅读您的代码。