this
this
키워드는 해당 클래스와 해당클래스로 인스턴스화된 객체를 가르키게 된다.
우리가 특정한 메서드를 호출하게되면 보이지는 않지만 해당 객체까지 같이 넘겨주게 된다.
하지만 this
는 생략이 가능하다.
또한 정적메서드 static
일 경우는 this
키워드를 사용 할 수 없다. static
메서드 자체가 해당 클래스내에서 공통으로 사용하는 메서드이기 때문이다.
public class Sample { string name; int age; int count; public Sample(string _name, int _age, int _count) { this.name = _name; age = _age; count = _count; } public void Hello() { // Console.WriteLine($"Hello My Name is {this.name}"); Console.WriteLine($"Hello My Name is {name}"); } // static 메서드는 this 키워드를 사용 할 수 없다. public static void agePrint() { Console.WriteLine($"And Age is {age}"); } } class Program { static void Main(string[] args) { Sample sample1 = new Sample("test1", 1, 2); Sample sample2 = new Sample("test2", 2, 4); // 각각 실행시에 자신의 맴버객체를 던져주지만 sample1.Hello(); sample2.Hello(); // agePrint 메서드의 경우 정적이기 때문에 실행할수없다. // 누구의 age이기 모르기 때문이다. } }
this
의 두번째 기능은 생성자 여러개를 동시에 호출 하는 것이다.
해당 생성자 뒤에 this
키워드를 적어주고 인자값을 던져주면 된다.
이 경우는 생성자 뒤에 있는 파라미터로 호출한 생성자 부터 실행된다.
public class Sample { public string name; public int age; public Sample() : this("name") { Console.WriteLine("Contructor #1"); } public Sample(string _name) : this("name", 1) { Console.WriteLine("Contructor #2"); this.name = _name; } public Sample(string _name, int _age) { Console.WriteLine("Contructor #3"); this.name = _name; this.age = _age; } } class Program { static void Main(string[] args) { Sample sample = new Sample(); Console.WriteLine(sample.name); Console.WriteLine(sample.age); } }

'C# > Basic' 카테고리의 다른 글
상속 (inheritance) (0) | 2021.02.25 |
---|---|
접근 제한자 (Access Modifier) (0) | 2021.02.14 |
getters & setters (0) | 2021.02.07 |
구조체 (struct) (0) | 2021.02.06 |
정적 생성자 (static constructor) (0) | 2021.02.02 |
댓글
이 글 공유하기
다른 글
-
상속 (inheritance)
상속 (inheritance)
2021.02.25 -
접근 제한자 (Access Modifier)
접근 제한자 (Access Modifier)
2021.02.14 -
getters & setters
getters & setters
2021.02.07 -
구조체 (struct)
구조체 (struct)
2021.02.06
댓글을 사용할 수 없습니다.