본문 바로가기

유니티 프로그래밍/C# 프로그래밍

C# this 키워드

this 키워드는 불려진 메서드의 클래스가 갖고 있는 변수나 메서드를 뜻한다.

 

햇갈리기 쉬우니 아래의 예제로 잘 이해해둘 것.

class Employee
{
    private string Name;
    private string Position;

    public void SetName(string Name)
    {
        this.Name = Name; // 여기서 this.Name은 위 3번째 행의 Name 변수를 뜻함.(그 뒤의 Name은 이 메서드인 SetName의 파라메터이다.
    }

    public string GetName()
    {
        return Name;
    }
    public void SetPosition(string Position)
    {
        this.Position = Position;
    }
    public string GetPosition()
    {
        return this.Position;
    }
}
class MyApp
{
    static void Main(string[] args)
    {
        Employee pooh = new Employee();
        pooh.SetName("Pooh");
        pooh.SetPosition("Waiter");
        Console.WriteLine($"{pooh.GetName()} {pooh.GetPosition()}");

        Employee tigger = new Employee();
        tigger.SetName("Tigger");
        tigger.SetPosition("Cleaner");
        Console.WriteLine($"{tigger.GetName()} {tigger.GetPosition()}");
    }
}