2010-11-14 234 views
0

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

所以这是不可能的,没有人知道该怎么称呼我的构造函数来设置内部代码参数?目前我从另一个构造函数存储对象的副本并复制所有的属性,这真的很烦人。

回答

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;  
    } 

}

为什么不能你准备的说法?

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;  
    }  
} 

,如果它的价值是依赖于其他外部状态,那么你可能会重新考虑你的设计...为什么要求在构造函数之前没有计算它第一名?

+0

不要想着把preperation放在一个单独的方法,它不是理想的,但它会工作,谢谢。 – MrFox 2010-11-14 22:28:46

+0

并且取决于它的复杂程度,它也可以在this()内部表达。()cpnstruction – 2010-11-14 22:33:18

+0

只是一个小提示:第二种方法中'PrepareArgument'必须是'static'。 – 2015-01-28 10:14:06

0

如果你想调用一个构造函数,但不能从头开始,唯一的办法就是定义一个私人的Initialize方法。看起来你正在构造函数中做“真正的工作”,这不是构造函数的任务。你应该想出一种不同的方式来实现你的目标,因为你的方式严格禁止调试和其他人阅读你的代码。

+0

为什么我们在同一主题中讨论标题和C#? (不是你的OP) – 2010-11-14 22:17:24

+0

我的意思是构造函数的头部,即。构造函数链,这应该与他在谈论的一样。 – Femaref 2010-11-14 22:36:35

1

听起来有点重构会有帮助。虽然你不能做准确的你想做什么,总是有替代品。我意识到你的实际代码可能比你给出的代码更复杂,所以以此为例来重构你的问题。将所有常见代码提取到新的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; 
    } 
}