C#문법

[C#문법] Part15 this 키워드

BlackWolfDev 2024. 10. 12. 14:02

[ 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
반응형