'this' 키워드
Coddy C# 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨 — 70개 중 4번째.
this 키워드는 클래스의 현재 인스턴스를 가리킵니다. 이것은 인스턴스 멤버에 접근하고 이름이 같은 매개변수와 필드를 구분하는 데 사용됩니다.
필드와 매개변수를 구분하기 위해 this를 사용하세요
public class Person
{
private string name;
private int age;
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
}this가 없으면 매개변수가 필드를 가리게 됩니다.
// 예상대로 작동하지 않습니다
public Person(string name, int age)
{
name = name; // 매개변수를 자기 자신에게 할당합니다!
age = age; // 매개변수를 자기 자신에게 할당합니다!
}속성과 함께 this를 사용하세요.
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
public Product(string name, decimal price)
{
this.Name = name;
this.Price = price;
}
public void DisplayInfo()
{
Console.WriteLine($"{this.Name}: ${this.Price}");
}
}동일한 클래스 내의 다른 생성자를 호출하려면 this를 사용하세요.
public class Rectangle
{
public int Width { get; set; }
public int Height { get; set; }
public Rectangle(int width, int height)
{
this.Width = width;
this.Height = height;
}
// Constructor for squares
public Rectangle(int size) : this(size, size)
{
}
}사용 예시:
Rectangle rect = new Rectangle(5, 10);
Rectangle square = new Rectangle(5); // 5x5를 생성합니다this 키워드는 항상 현재 객체 인스턴스를 참조합니다. 매개변수 이름이 필드 또는 속성 이름과 일치할 때 특히 유용하며, 코드를 더 명확하게 만들고 오류를 방지합니다.
챌린지
중급매개변수 값을 속성에 할당하기 위해 this 키워드를 사용하는 생성자를 추가하여 Product 클래스를 완성하세요. 또한 속성에 접근하기 위해 this를 사용하여 GetDescription() 메서드를 구현하세요.
GetDescription() 메서드는 "{Name} costs ${Price}"를 반환해야 합니다.
치트 시트
this 키워드는 클래스의 현재 인스턴스를 참조하며 인스턴스 멤버에 액세스하는 데 사용됩니다.
이름이 같은 필드와 매개변수를 구분하려면 this를 사용하세요:
public class Person
{
private string name;
private int age;
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
}this가 없으면 매개변수가 필드를 가리고 자기 자신에게 할당됩니다:
// 예상대로 작동하지 않습니다
public Person(string name, int age)
{
name = name; // 매개변수를 자기 자신에게 할당합니다!
age = age; // 매개변수를 자기 자신에게 할당합니다!
}속성(properties)과 함께 this를 사용하세요:
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
public Product(string name, decimal price)
{
this.Name = name;
this.Price = price;
}
public void DisplayInfo()
{
Console.WriteLine($"{this.Name}: ${this.Price}");
}
}동일한 클래스의 다른 생성자를 호출하려면 this를 사용하세요 (생성자 체이닝):
public class Rectangle
{
public int Width { get; set; }
public int Height { get; set; }
public Rectangle(int width, int height)
{
this.Width = width;
this.Height = height;
}
// 정사각형을 위한 생성자
public Rectangle(int size) : this(size, size)
{
}
}
Rectangle square = new Rectangle(5); // 5x5를 생성합니다직접 해보기
using System;
class Program
{
static void Main()
{
string name = Console.ReadLine();
decimal price = decimal.Parse(Console.ReadLine());
Product product = new Product(name, price);
Console.WriteLine($"Product: {product.Name}");
Console.WriteLine($"Price: ${product.Price}");
Console.WriteLine(product.GetDescription());
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.