this キーワードの使用
this キーワードには、2 つの使用方法があります。
this をドット表記で括弧をつけずに使用し、表示されるクラスの現在のインスタンスを表すことができます。this キーワードのこの形式は、インスタンス変数とメソッドへのアクセスに使用します。次に例を示します。
1public class myTestThis {
2
3string s;
4 {
5 this.s = 'TestString';
6 }
7}上記の例の場合、クラス myTestThis では、インスタンス変数 s が宣言されています。この変数の値を初期化コードで設定するときは、this キーワードを使用します。
また、コンストラクタチェーニングの実行で this キーワードを使用することもできます。コンストラクタチェーニングとは、1 つのコンストラクタから別のコンストラクタをコールすることです。この形式では、this キーワードを括弧と共に使用します。次に例を示します。
1public class testThis {
2
3// First constructor for the class. It requires a string parameter.
4 public testThis(string s2) {
5 }
6
7// Second constructor for the class. It does not require a parameter.
8// This constructor calls the first constructor using the this keyword.
9 public testThis() {
10 this('None');
11 }
12}コンストラクタでのコンストラクタチェーニングの実行で this キーワードを使用する場合、コンストラクタの 1 つ目のステートメントに記述する必要があります。