C# 如何在其他构造函数中调用构造函数?
我的类有很多属性,我的一个构造函数设置了所有属性,我希望默认构造函数调用另一个并使用设置的属性。但是我需要先准备参数,所以从标题调用它不会有帮助 以下是我想做的:C# 如何在其他构造函数中调用构造函数?,c#,constructor,C#,Constructor,我的类有很多属性,我的一个构造函数设置了所有属性,我希望默认构造函数调用另一个并使用设置的属性。但是我需要先准备参数,所以从标题调用它不会有帮助 以下是我想做的: public class Test { private int result, other; // The other constructor can be called from header, // but then the argument cannot be prepared.
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;
}
}
所以这是不可能的,有人知道如何调用我的构造函数在代码中设置参数吗?目前,我正在存储另一个构造函数的对象副本并复制所有属性,这真的很烦人。如果你想调用一个构造函数,但不能从头中调用,唯一的方法就是定义一个私有初始化方法。看起来您正在构造函数中进行真正的工作,这不是构造函数的任务。您应该考虑一种不同的方式来实现您的目标,因为您的方式严重禁止调试和其他人阅读您的代码。听起来稍微重构一下会有所帮助。虽然你不能完全做你想做的事,但总有其他选择。我意识到您的实际代码可能比您给出的代码更复杂,所以以这个重构问题为例。将所有公共代码提取到新的SetVariables方法中
对。只需在第一次调用中传递值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;
}
}
如果它的值依赖于其他外部状态,那么您可能会重新考虑您的设计。。。为什么不在调用构造函数之前计算它呢 为什么我们在同一主题中讨论头和C?不是你,因为OPI指的是构造器的头,即构造器链接,这也应该和他说的一样。不要想用一个单独的方法来做准备,这并不理想,但会起作用,谢谢。这取决于它有多复杂,它也可以在这个cpnstruction内部表达,只是一个小提示:在第二种方法中,PrepareArgument必须是静态的。
public class Test
{
const int result = 1;
private int result, other;
public Test()
{
// Do some other stuff.
other = 2;
}
}