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 に答える