C#
210525 C#_this() 생성자
S_pot
2021. 5. 25. 10:29
// this()생성자 사용전
public Smart(string Name)
{
this.Name = Name;
this.Address = "미기입";
}
public Smart(string Name, string Address)
{
this.Name = Name;
this.Address = Address;
}
public Smart()
{
this.Name = "무명";
this.Address = "미기입";
}
}
class Program
{
static void Main(string[] args)
{
Smart aSmart = new Smart("홍길동", "부산");
}
}
// this() 생성자 적용
using System;
// this() 생성자: 생성자에서 다른 생성자를 호출
// 메서드 하나에서 처리하고 오버로딩을 통해
class Smart
{
private string Name;
private string Address;
public Smart(string Name) : this(Name, "미기입")
{
Console.WriteLine("매개변수 1개짜리 생성자");
}
public Smart(string Name, string Address)
{
this.Name = Name;
this.Address = Address;
Console.WriteLine("매개변수 2개짜리 생성자");
}
public Smart() : this("무명", "미기입")
{
Console.WriteLine("디폴트 생성자");
}
}
class Program
{
static void Main(string[] args)
{
Smart aSmart = new Smart("홍길동", "부산");
}
}
출력값