70

我如何在 C# 中使用构造函数,如下所示:

public Point2D(double x, double y)
{
    // ... Contracts ...

    X = x;
    Y = y;
}

public Point2D(Point2D point)
{
    if (point == null)
        ArgumentNullException("point");
    Contract.EndContractsBlock();

    this(point.X, point.Y);
}

我需要它不要从另一个构造函数复制代码......

4

3 回答 3

207
public Point2D(Point2D point) : this(point.X, point.Y) { }
于 2011-04-05T17:13:46.287 回答
69

您可以将通用逻辑分解为私有方法,例如Initialize从两个构造函数调用的调用。

由于您要执行参数验证这一事实,您不能诉诸构造函数链接。

例子:

public Point2D(double x, double y)
{
    // Contracts

    Initialize(x, y);
}

public Point2D(Point2D point)
{
    if (point == null)
        throw new ArgumentNullException("point");

    // Contracts

    Initialize(point.X, point.Y);
}

private void Initialize(double x, double y)
{
    X = x;
    Y = y;
}
于 2011-04-05T17:16:01.133 回答
6

也许你的课还不够完整。就个人而言,我在所有重载的构造函数中都使用了私有 init() 函数。

class Point2D {

  double X, Y;

  public Point2D(double x, double y) {
    init(x, y);
  }

  public Point2D(Point2D point) {
    if (point == null)
      throw new ArgumentNullException("point");
    init(point.X, point.Y);
  }

  void init(double x, double y) {
    // ... Contracts ...
    X = x;
    Y = y;
  }
}
于 2011-04-05T17:20:51.823 回答