在C#中,可以使用this关键字来表示当前对象,在日常开发中,可以使用this关键字来访问类内成员的属性和函数。不仅如此,this关键字还有其他几种用法,下面提供一些示例来说明它们。
1)用this表示当前类的一个对象
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) 使用该关键字作为类索引器。
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) 使用此关键字作为基本类型的扩展方法。
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# チュートリアル |ドットネットトリック




![2021 年如何设置 Raspberry Pi Web 服务器 [指南]](https://i0.wp.com/pcmanabu.com/wp-content/uploads/2019/10/web-server-02-309x198.png?w=1200&resize=1200,0&ssl=1)

