C# では、 this キーワードを使用して現在のオブジェクトを表すことができ、日常の開発では、 this キーワードを使用してクラス内のメンバーのプロパティと関数にアクセスできます。それだけでなく、 this キーワードには他にもいくつかの使用法があり、それらを示すためにいくつかの例を以下に示します。
1) これを使用して現在のクラスのオブジェクトを表します
using System;
namespace it-kiso.com
{
class Demo
{
static void Main(string[] args)
{
Website site = new Website("IT基礎","https://it-kiso.com/");
site.Display();
}
}
public class Website
{
private string name; // 名称
private string url; // URL
public Website(string n, string u){
this.name = n;
this.url = u;
}
public void Display(){ // 表示
Console.WriteLine(name +" "+ url);
}
}
}
操作の結果は次のようになります。
IT基礎 https://it-kiso.com/
2) this キーワードを使用してコンストラクターを連結する
using System;
namespace it-kiso.com
{
class Demo
{
static void Main(string[] args)
{
Test test = new Test("IT基礎");
}
}
public class Test
{
public Test()
{
Console.WriteLine("引数のないコンストラクタ");
}
// ここでの this() は引数のないコンストラクタ Test() を表している
// Test() が先に実行され、次に Test(string text) が実行される
public Test(string text) : this()
{
Console.WriteLine(text);
Console.WriteLine("インスタンスコンストラクタ");
}
}
}
3) this キーワードをクラス インデクサーとして使用します。
using System;
namespace it-kiso.com
{
class Demo
{
static void Main(string[] args)
{
Test a = new Test();
Console.WriteLine("Temp0:{0}, Temp1:{1}", a[0], a[1]);
a[0] = 15;
a[1] = 20;
Console.WriteLine("Temp0:{0}, Temp1:{1}", a[0], a[1]);
}
}
public class Test
{
int Temp0;
int Temp1;
public int this[int index] // インデクサ
{
get // ゲッター
{
return (0 == index) ? Temp0 : Temp1;
}
set // セッター
{
if (0==index) // インデックス指定
Temp0 = value;
else
Temp1 = value;
}
}
}
}
操作の結果は次のようになります。
Temp0:0, Temp1:0
Temp0:15, Temp1:20
4) this キーワードをプリミティブ型の拡張メソッドとして使用します。
using System;
namespace it-kiso.com
{
class Demo
{
static void Main(string[] args)
{
string str = "IT基礎";
string newstr = str.ExpandString();
Console.WriteLine(newstr);
}
}
public static class Test
{
public static string ExpandString(this string name)
{
return name+" https://it-kiso.com/";
}
}
}
操作の結果は次のようになります。
IT基礎 https://it-kiso.com/
「 C# のキーワード」についてわかりやすく解説!絶対に観るべきベスト2動画
C#コードをスッキリさせる書き方
C# 2021 のアクセス修飾子 |アクセス修飾子の例 |高度な C# チュートリアル |ドットネットトリック