C#のthisについて詳しく解説

C#のthisについて詳しく解説

thisとは?

C#の「this」は、現在のインスタンスを指すキーワードです。クラスのメンバー関数内で使用し、インスタンスのメンバーへアクセスする際に利用されます。

class Sample {
    private int value;
    
    public void SetValue(int value) {
        this.value = value; // thisを使うことでインスタンス変数を明示
    }
}

コンストラクタ内でのthisの使用

コンストラクタのオーバーロードを簡潔に書くために「this」を使用できます。

class Person {
    public string Name;
    public int Age;
    
    public Person(string name) : this(name, 0) { }
    
    public Person(string name, int age) {
        this.Name = name;
        this.Age = age;
    }
}

インスタンス変数との区別

ローカル変数とインスタンス変数が同名の場合、thisを使ってインスタンス変数を区別できます。

class MyClass {
    private int number;
    
    public void SetNumber(int number) {
        this.number = number; // ローカル変数と区別するためにthisを使用
    }
}

メソッドチェーン

メソッドが自身のインスタンスを返すことで、メソッドチェーンを実現できます。

class Calculator {
    private int total = 0;
    
    public Calculator Add(int value) {
        this.total += value;
        return this;
    }
    
    public Calculator Subtract(int value) {
        this.total -= value;
        return this;
    }
    
    public int GetTotal() {
        return this.total;
    }
}

// 使用例
Calculator calc = new Calculator();
int result = calc.Add(10).Subtract(5).GetTotal();

現在のインスタンスを返す

「this」を返すことで、現在のオブジェクトを呼び出し元に渡せます。

class Person {
    private string name;
    
    public Person SetName(string name) {
        this.name = name;
        return this;
    }
}

拡張メソッドにおけるthis

拡張メソッドでは、「this」を使ってメソッドを追加する対象を指定します。

static class StringExtensions {
    public static string ToCustomFormat(this string str) {
        return "*** " + str + " ***";
    }
}

// 使用例
string message = "Hello";
Console.WriteLine(message.ToCustomFormat()); // *** Hello ***

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です