C#构造函数重载

时间:2011-04-05 17:12:30

标签: c# constructor constructor-overloading

如何在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);
}

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

3 个答案:

答案 0 :(得分:170)

public Point2D(Point2D point) : this(point.X, point.Y) { }

答案 1 :(得分:60)

您可以将您的公共逻辑分解为私有方法,例如从两个构造函数调用的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;
}

答案 2 :(得分:5)

也许你的班级不完整。就个人而言,我使用一个私有的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;
  }
}