this
지금까지 클래스 내부에서 멤버에 접근했을때 this를 생략하고 쓰고 있었다고 봐도 무방하다.
이런 경우엔 this를 써봤자 코드만 늘어날 뿐 써야할 이유가 없다.
생성자를 여러개 오버로딩 할 경우 모든 변수값을 받는 하나의 생성자를 만들어두고 this를 쓰면
중복코드를 상당히 줄일수 있다.
주의 해야될게 this는 new로 할당된 내부 객체를 가리키는 내부 식별자 이므로
정적멤버는 this 예약어를 사용할 수 없다.
예제) 여러개의 생성자 오버로딩 코드 줄이기
class Car
{
int iSpeed; // 속도
string sColor; // 색상
string sName; // 이름
string sVender; // 제조사
public Car() : this(0, "화이트", "미정", "미정")
{
//Car(0, "화이트", "미정", "미정");
//iSpeed = 0;
//sColor = "화이트";
//sName = "미정";
//sVender = "미정";
}
public Car(int iSpeed) : this(iSpeed, "화이트", "미정", "미정")
{
//this.iSpeed = iSpeed;
// sColor = "화이트";
//sName = "미정";
//sVender = "미정";
}
public Car(string sColor) : this(0, sColor, "미정", "미정")
{
//this.iSpeed = iSpeed;
//this.sColor = sColor;
//sName = "미정";
//sVender = "미정";
}
public Car(string sColor, string sName) : this(0, sColor, sName, "미정")
{
//iSpeed = 0;
//this.sColor = sColor;
//this.sName = sName;
//sVender = "미정";
}
public Car(string sColor, string sName, string sVender) : this(0, sColor, sName, sVender)
{
//iSpeed = 0;
//this.sColor = sColor;
//this.sName = sName;
//this.sVender = sVender;
}
public Car(int iSpeed, string sColor, string sName, string sVender)
{
this.iSpeed = iSpeed;
this.sColor = sColor;
this.sName = sName;
this.sVender = sVender;
}
public void Print()
{
Console.WriteLine("속 도 : {0}", iSpeed);
Console.WriteLine("색 상 : {0}", sColor);
Console.WriteLine("이 름 : {0}", sName);
Console.WriteLine("제조사 : {0}", sVender);
Console.WriteLine("------------");
}
}
class Program
{
static void Main(string[] args)
{
Car aCar = new Car();
aCar.Print();
aCar = new Car(80);
aCar.Print();
aCar = new Car("빨강");
aCar.Print();
aCar = new Car("빨강", "그렌저");
aCar.Print();
aCar = new Car("빨강","그렌저","현대");
aCar.Print();
aCar = new Car(100,"빨강", "그렌저", "현대");
aCar.Print();
}
}
'컴퓨터 > C#' 카테고리의 다른 글
[C#] 다형성.메서드 오버라이드 (0) | 2020.06.03 |
---|---|
[C#] base (super) (0) | 2020.06.02 |
[C#] Array 타입 (0) | 2020.06.02 |
[C#] Object 타입 (0) | 2020.06.02 |
[C#] 캡슐화, 상속 (0) | 2020.06.01 |