C# this关键字
在 C# 中,可以使用 this 关键字来表示当前对象,日常开发中我们可以使用 this 关键字来访问类中的成员属性以及函数。不仅如此 this 关键字还有一些其它的用法,下面就通过一些示例来分别演示一下。
1) 使用 this 表示当前类的对象
using System;
namespace net.yinzhong
{
class Demo
{
static void Main(string[] args)
{
Website site = new Website("C语言","http://www.yinzhong.net/");
site.Display();
}
}
public class Website
{
private string name;
private string url;
public Website(string n, string u){
this.name = n;
this.url = u;
}
public void Display(){
Console.WriteLine(name +" "+ url);
}
}
}
运行结果如下:
C语言 http://www.yinzhong.net/
2) 使用 this 关键字串联构造函数
using System;
namespace net.yinzhong
{
class Demo
{
static void Main(string[] args)
{
Test test = new Test("C语言");
}
}
public class Test
{
public Test()
{
Console.WriteLine("无参构造函数");
}
// 这里的 this()代表无参构造函数 Test()
// 先执行 Test(),后执行 Test(string text)
public Test(string text) : this()
{
Console.WriteLine(text);
Console.WriteLine("实例构造函数");
}
}
}
运行结果如下:
无参构造函数 C语言 实例构造函数
3) 使用 this 关键字作为类的索引器
using System;
namespace net.yinzhong
{
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 net.yinzhong
{
class Demo
{
static void Main(string[] args)
{
string str = "C语言";
string newstr = str.ExpandString();
Console.WriteLine(newstr);
}
}
public static class Test
{
public static string ExpandString(this string name)
{
return name+" http://www.yinzhong.net/";
}
}
}
运行结果如下:
C语言 http://www.yinzhong.net/

