在C#中从另一个体中调用一个构造函数

tom*_*tom 49 c# constructor

我需要从另一个构造函数中调用一个构造函数.我怎样才能做到这一点?

基本上

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)

  • 请注意,通常,setup方法无法写入`readonly`变量,但构造函数可以将`readonly`变量作为`ref`参数传递给setup方法,然后该方法可以写入`ref`参数,即使它们是只读变量. (12认同)
  • 在大多数情况下,Setup方法应该是私有的 (5认同)

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在其他构造函数的参数内使用,包括调用实例方法 - 但您可以调用静态方法.
  • 任何实例变量初始化链接的调用之前执行.

我在关于构造函数链接的文章中有更多的信息.

  • @DanielHilgarth:是的.有一个通用的扩展方法,它检查无效但是返回原始值.然后你可以做这个(c.ThrowIfNull("c").Items)` (2认同)

Mar*_*uła 6

要明确地调用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这样的方式时给出的值不能依赖于其他构造函数的参数,它们必须以其他方式解析(它们不需要是常量,尽管如上面编辑的代码示例中那样).如果xy是从中计算出来的s,你可以这样做:

public foo (string s) : this(GetX(s), GetY(s))

  • 小话:public foo(string s):这个(x,y)不起作用.public foo(string s,int x,int y):this(x,y)将编译 (2认同)