コンストラクタの呼び出し
Hogeクラスのコンストラクタを定義する。
クラス内で定義された他のコンストラクタを呼ぶにはthisを利用する。
この場合、thisで呼び出したコンストラクタがどのタイミングで呼び出されるか調べた。
public class Hoge { public Hoge() : this(3) { Console.WriteLine("Hoge() called"); } public Hoge(int n) : this(new string[]{"hoge"}) { Console.WriteLine("Hoge(int n) called"); } public Hoge(string[] items) { Console.WriteLine("Hoge(string[] items) called"); } }
以下は呼び出し元のコード
new Hoge(); new Hoge(3); new Hoge(new string[] { "hoge", "auau" });
出力は以下のようになった。
Hoge(string items) called Hoge(int x) called Hoge() called Hoge(string items) called Hoge(int x) called Hoge(string[] items) called
以上より、thisで呼び出されるコンストラクタの後に通常の処理が実行されていることがわかる。