반응형
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
반응형
'Development Tip' 카테고리의 다른 글
인 텐트를 사용하여 활동에서 서비스로 데이터 전달 (0) | 2020.11.25 |
---|---|
JSP에서 날짜 변환 및 형식 지정 (0) | 2020.11.25 |
Sourcetree의 .gitignore 파일이 작동하지 않습니다. (0) | 2020.11.25 |
초 단위로 주어진 시간 간격을 사람이 읽을 수있는 형식으로 변환 (0) | 2020.11.25 |
시간 O (n)에서 배열에서 중복 요소 찾기 (0) | 2020.11.25 |