Development Tip

C # 생성자 오버로딩

yourdevel 2020. 11. 25. 21:18
반응형

C # 생성자 오버로딩


다음과 같이 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);
}

다른 생성자에서 코드를 복사하지 않으려면 ...


예를 들어 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;
}

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

수업이 완전히 완료되지 않았을 수 있습니다. 개인적으로 오버로드 된 모든 생성자와 함께 private 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;
  }
}

참고 URL : https://stackoverflow.com/questions/5555715/c-sharp-constructors-overloading

반응형