如何调用其它构造函数中构造? [英] How call constructor inside other constructor?
问题描述
我的类有相当长的一段属性和我的构造函数中的一个集所有这些,我想默认的构造函数调用此另一个和使用属性集。但我需要先准备好参数,所以从头部不会帮助称之为
My class has quite some properties and one of my constructors sets them all, I want the default constructor to call this other one and use the set properties. But I need to prepare arguments first, so calling it from the header won't help.
下面是我想做什么:
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;
}
}
所以这是不可能的,没有人知道如何叫我的构造函数来设置里面的代码参数?目前,我存储从其他构造对象的副本,并复制所有的属性,它是真烦人。
So this is not possible, does anyone know how to call my constructor to set parameters inside code? Currently I'm storing a copy of the object from the other constructor and copying all the properties, it's really annoying.
推荐答案
是的。刚刚通过的第一个电话
Yes. just pass the value 1 in the first call
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;
}
}
}
而你为什么不能做准备的说法?
And why can't you prepare the argument?
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要被称为从默认的构造函数,那么就可以不依赖于任何参数传递。如果它是一个常量,只是让一个恒定的...
or... if the prepareArgument is to be called from the default constructor, then it cannot be dependent on any passed in arguments. If it is a constant, just make it a constant ...
public class Test
{
const int result = 1;
private int result, other;
public Test()
{
// Do some other stuff.
other = 2;
}
}
,如果它的值是依赖于其它外部的状态,然后你可能会重新考虑你的设计...为什么调用构造函数首先之前不算呢?
if it's value is dependent on other external state, then you might rethink your design... Why not calculate it before calling the constructor in the first place?
这篇关于如何调用其它构造函数中构造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!