this The keyword points to the current instance of the class and is also used as a modifier for the first parameter of an extension method.
1. this는 객체가 자신을 지칭할 때 사용하는 키워드이다.
클래스 내부에서 필드명과, 메서드의 매게변수의 이름이 동일할 때, this 키워드로 모호성을 제거할 수 있다.
this가 붙은 변수는 클래스 자신의 필드이며 그 외는 매개 변수이다.
using System; namespace This { class Employee { private string Name; private string Position; public void SetName(string Name) { this.Name = Name; } public string GetName() { return Name; } public void SetPosition(string Position) { this.Position = Position; } public string GetPosition() { return this.Position; } } class Program { static void Main(string[] args) { Employee pooh = new Employee(); pooh.SetName("Pooh"); pooh.SetPosition("Waiter"); Console.WriteLine("{0} {1}", pooh.GetName(), pooh.GetPosition()); Employee tigger = new Employee(); tigger.SetName("Tigger"); tigger.SetPosition("Cleaner"); Console.WriteLine("{0} {1}", tigger.GetName(), tigger.GetPosition()); } } }
2. this() 생성자는 자기 자신의 생성자를 가리킨다.
아래의 예제처럼 this() 생성자를 사용하여 같은 클래스 안에 있는 생성자들을 서로 호출할 수 있어 효율적인 코드가 가능하다.
using System; namespace ThisConstructor { class MyClass { int a, b, c; public MyClass() { this.a = 5425; Console.WriteLine("MyClass()"); } public MyClass(int b) : this() { this.b = b; Console.WriteLine("MyClass({0})", b); } public MyClass(int b, int c) : this(b) { this.c = c; Console.WriteLine("MyClass({0}, {1})", b, c); } public void PrintFields() { Console.WriteLine("a: {0}, b: {1}, c: {2}", a, b, c); } } class Program { static void Main(string[] args) { MyClass a = new MyClass(); a.PrintFields(); Console.WriteLine(); MyClass b = new MyClass(1); b.PrintFields(); Console.WriteLine(); MyClass c = new MyClass(10, 20); c.PrintFields(); } } }
'Language & etc > C#' 카테고리의 다른 글
readonly vs const (0) | 2022.02.15 |
---|---|
[C#] 접근 제한자 , 어셈블리란? (0) | 2022.01.06 |
[C#] .NET FrameWork( 닷넷 프레임워크) 이란 무엇인가? (0) | 2022.01.06 |