C#의 "this" 키워드는 클래스의 현재 인스턴스를 참조하는 데 사용됩니다. 메소드 매개변수와 클래스 필드가 동일한 이름을 가지고 있는 경우 이를 구별하는 데에도 사용됩니다.
"this" 키워드의 또 다른 사용법은 같은 클래스의 생성자에서 다른 생성자를 호출하는 것입니다.
여기에서는 예를 들어 id, Name, Age 및 Subject와 같은 Students의 레코드를 표시하고 있습니다. 현재 클래스의 필드를 참조하기 위해 C#에서 "this" 키워드를 사용했습니다 -
public Student(int id, String name, int age, String subject) {
this.id = id;
this.name = name;
this.subject = subject;
this.age = age;
} 예시
C#에서 "this" 키워드로 작업하는 방법을 배우기 위해 전체 예제를 살펴보겠습니다. −
using System.IO;
using System;
class Student {
public int id, age;
public String name, subject;
public Student(int id, String name, int age, String subject) {
this.id = id;
this.name = name;
this.subject = subject;
this.age = age;
}
public void showInfo() {
Console.WriteLine(id + " " + name+" "+age+ " "+subject);
}
}
class StudentDetails {
public static void Main(string[] args) {
Student std1 = new Student(001, "Jack", 23, "Maths");
Student std2 = new Student(002, "Harry", 27, "Science");
Student std3 = new Student(003, "Steve", 23, "Programming");
Student std4 = new Student(004, "David", 27, "English");
std1.showInfo();
std2.showInfo();
std3.showInfo();
std4.showInfo();
}
}