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

MrF*_*Fox 0 c# constructor

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

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

Cha*_*ana 5

是.只需在第一次调用中传递值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;    
    }
Run Code Online (Sandbox Code Playgroud)

}

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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