我需要从另一个构造函数中调用一个构造函数。我怎么能这样做?
基本上
class foo {
public foo (int x, int y)
{
}
public foo (string s)
{
// ... do something
// Call another constructor
this (x, y); // Doesn't work
foo (x, y); // neither
}
}
答案 0 :(得分:68)
你不能。
你必须找到一种链接构造函数的方法,如:
public foo (int x, int y) { }
public foo (string s) : this(XFromString(s), YFromString(s)) { ... }
或将构造代码移动到常用的设置方法中,如下所示:
public foo (int x, int y) { Setup(x, y); }
public foo (string s)
{
// do stuff
int x = XFromString(s);
int y = YFromString(s);
Setup(x, y);
}
public void Setup(int x, int y) { ... }
答案 1 :(得分:34)
this(x, y)
是正确的,但它必须在构造函数体的开始之前:
public Foo(int x, int y)
{
...
}
public Foo(string s) : this(5, 10)
{
}
请注意:
this
或base
- 当然,构造函数可以链接到另一个构造函数。this
,包括调用实例方法 - 但可以调用静态方法。我在article about constructor chaining中有更多信息。
答案 2 :(得分:6)
要显式调用base和this类构造函数,你需要使用下面给出的语法(注意,在C#中你不能用它来初始化C ++中的字段):
class foo
{
public foo (int x, int y)
{
}
public foo (string s) : this(5, 6)
{
// ... do something
}
}
//编辑:注意,您在样本中使用了x,y。当然,在调用ctor这样的方式时给出的值不能依赖于其他构造函数的参数,它们必须以其他方式解析(它们不需要是常量,尽管如上面编辑的代码示例中那样)。如果从x
计算y
和s
,您可以这样做:
public foo (string s) : this(GetX(s), GetY(s))
答案 3 :(得分:1)
不支持此功能 - 请参阅 Constructors in C# 。
但是,您可以实现从不同构造函数调用的公共(私有)方法...
答案 4 :(得分:1)
我自己遇到过这个问题一两次...我最终不得不将其他构造函数中需要的任何逻辑提取到private void
方法并在两个地方调用它。
class foo
{
private void Initialize(int x, int y)
{
//... do stuff
}
public foo(int x, int y)
{
Initialize(x, y);
}
public foo(string s_
{
// ... do stuff
Initialize(x, y)
// ... more stuff
}
}
答案 5 :(得分:0)
在MSDN中,MethodBase.Invoke
的{{3}}中有一条注释
如果此方法重载用于调用实例构造函数,则 为obj提供的对象被重新初始化;也就是说,所有实例 初始化程序被执行。返回值为空。如果上课 构造函数被调用,该类被重新初始化;也就是说,所有阶级 初始化程序被执行。返回值为空。
即您可以通过反射来获取Constructor的方法,并在新构造函数的主体中通过Invoke
对其进行调用。 但是我没有尝试。而且,当然,此解决方案有很多缺点。