C# の別のコンストラクターからコンストラクターを呼び出す
 
このチュートリアルでは、C# で同じクラスの別のコンストラクターから 1つのコンストラクターを呼び出すメソッドについて説明します。
C# で this キーワードを使用して、同じクラスの別のコンストラクターから 1つのコンストラクターを呼び出す
    
クラスに複数のコンストラクターがあり、あるコンストラクターを別のコンストラクターから呼び出したい場合は、C# で this キーワードを使用できます。this キーワードは、C# の現在のクラスのインスタンスへの参照です。次のコード例は、C# で this キーワードを使用して、同じクラスの別のコンストラクターからクラスの 1つのコンストラクターを呼び出す方法を示しています。
using System;
namespace call_another_constructor {
  class sample {
    public sample() {
      Console.WriteLine("Constructor 1");
    }
    public sample(int x) : this() {
      Console.WriteLine("Constructor 2, value: {0}", x);
    }
    public sample(int x, int y) : this(x) {
      Console.WriteLine("Constructor 3, value1: {0} value2: {1}", x, y);
    }
  }
  class Program {
    static void Main(string[] args) {
      sample s1 = new sample(12, 13);
    }
  }
}
出力:
Constructor 1
Constructor 2, value: 12
Constructor 3, value1: 12 value2: 13
3つの異なるコンストラクターを使用して sample クラスを作成しました。コンストラクターsample(int x, int y) はコンストラクターsample(int x) を呼び出し、this(x) を使用してパラメーターとして x を渡します。次に、コンストラクターsample(int x) は、コンストラクターsample() を this() で呼び出します。sample() コンストラクターは sample(int x) コンストラクターの前に実行され、sample(int x) コンストラクターは sample(int x, int y) コンストラクターの前に実行されます。
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn