'this' キーワード
CoddyのC#ジャーニー「オブジェクト指向プログラミング」セクションの一部 — レッスン 4/70。
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;
}
// 正方形用のコンストラクタ
public Rectangle(int size) : this(size, size)
{
}
}使用例:
Rectangle rect = new Rectangle(5, 10);
Rectangle square = new Rectangle(5); // 5x5を作成しますthisキーワードは常に現在のオブジェクトインスタンスを指します。これは、パラメータ名がフィールド名やプロパティ名と一致する場合に特に便利で、コードをより明確にし、エラーを防ぐことができます。
チャレンジ
中級Product クラスを完成させてください。プロパティに引数の値を代入するために this キーワードを使用するコンストラクタを追加します。また、プロパティにアクセスするために 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; // パラメータを自分自身に代入しています!
}プロパティで 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());
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。