我需要从另一个构造函数中调用一个构造函数.我怎样才能做到这一点?
基本上
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
}
}
Run Code Online (Sandbox Code Playgroud)
lad*_*dge 71
你不能.
你必须找到一种链接构造函数的方法,如:
public foo (int x, int y) { }
public foo (string s) : this(XFromString(s), YFromString(s)) { ... }
Run Code Online (Sandbox Code Playgroud)
或者将构造代码移动到常用的设置方法中,如下所示:
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) { ... }
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 35
this(x, y) 是的,但它必须在构造函数体的开始之前:
public Foo(int x, int y)
{
...
}
public Foo(string s) : this(5, 10)
{
}
Run Code Online (Sandbox Code Playgroud)
注意:
this或者base- 当然,构造函数可以链接到另一个构造函数.this在其他构造函数的参数内使用,包括调用实例方法 - 但您可以调用静态方法.我在关于构造函数链接的文章中有更多的信息.
要明确地调用base和this类构造函数,你需要使用下面给出的语法(注意,在C#中你不能用它来初始化C++中的字段):
class foo
{
public foo (int x, int y)
{
}
public foo (string s) : this(5, 6)
{
// ... do something
}
}
Run Code Online (Sandbox Code Playgroud)
//编辑:注意,您在样本中使用了x,y.当然,在调用ctor这样的方式时给出的值不能依赖于其他构造函数的参数,它们必须以其他方式解析(它们不需要是常量,尽管如上面编辑的代码示例中那样).如果x和y是从中计算出来的s,你可以这样做:
public foo (string s) : this(GetX(s), GetY(s))