[ this 키워드 ]
this 키워드는 인스턴스 자신을 가리킬때 사용된다.
죽, this 키워드를 사용하면 인스턴스 내부에서 자신의 멤버 변수나 멤버 메서드에 접근할 수 있다.
그냥 인스턴스의 멤버 변수와 멤버 메서드는 가져와도 상관없지만 코드의 가독성을 높일 수 있다.
그리고 멤버 변수와 매개변수의 이름이 같을 경우, this 키워드를 이용하면 구분하기 쉽다.
[ 구현 방법 ]
this.멤버변수 = 값;
this.멤버메서드();
this 키워드 뒤에 인스턴스가 가지고 있는 멤버 변수나 멤버 메서드를 불러올 수 있다.
[ 사용 방법 ]
public class GameCharacter
{
public string name;
public GameCharacter(string name)
{
this.name = name;
}
}
이런 식으로 멤버 변수와 매개변수의 이름이 같더라도 구분되게 코드를 구현할 수 있다.
[ 결과 화면 ]
public class GameCharacter
{
public string name;
public GameCharacter(string name)
{
this.name = name;
}
}
public class Program
{
private static void Main(string[] args)
{
GameCharacter gameCharacter = new GameCharacter("NPC");
Console.WriteLine("GameCharacter의 이름은: " + gameCharacter.name);
}
}
728x90
반응형
'C#문법' 카테고리의 다른 글
[C# 문법] Part17 const 키워드 (0) | 2025.02.02 |
---|---|
[C# 문법] Part16 static 한정자 (1) | 2024.10.19 |
[C#문법] Part14 new 연산자 (7) | 2024.10.09 |
[C#문법] Part13 생성자(Constructor)와 소멸자(Destructor) (4) | 2024.10.09 |
[C#문법] Part12 클래스(Class) (2) | 2024.10.04 |