一、this可以代表引用類的當(dāng)前實例,包括繼承而來的方法,通常可以省略。
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string Name, int Age)
{
this.Age = Age;
this.Name = Name;
}
}
這個不用多說,當(dāng)對象調(diào)用自己內(nèi)部函數(shù)的時候,用到對象使用this即可。
二、this關(guān)鍵字后面跟“:”符號,可以調(diào)用其它的構(gòu)造函數(shù)
//聲明有實現(xiàn)的構(gòu)造函數(shù)
public Person()
{
this.NAge = 100;
Console.WriteLine("我是超人!");
}
public Person(int nAge)
{
Console.WriteLine("超人的年齡{0}", nAge);
}
//使用this關(guān)鍵字調(diào)用了第二個一個參數(shù)的構(gòu)造函數(shù)
public Person(int nAge, string strName)
: this(1)
{
Console.WriteLine("我是叫{0}的超人,年齡{1}", strName, nAge);
}
我們創(chuàng)建該對象看看是否調(diào)用成功。在Main函數(shù)中添加如下代碼:
執(zhí)行會輸出:
超人的年齡1
我是叫強(qiáng)子的超人,年齡10
三、聲明索引器
索引器類型表示該索引器使用哪一類型的索引來存取數(shù)組或集合元素,可以是整數(shù),可以是字符串;this表示操作本對象的數(shù)組或集合成員,可以簡單把它理解成索引器的名字,因此索引器不能具有用戶定義的名稱。例如:
public class Person
{
string[] PersonList = new string[10];
public string this[int param]
{
get { return PersonList[param]; }
set { PersonList[param] = value; }
}
}
其中索引的數(shù)據(jù)類型必須與索引器的索引類型相同。例如:
Person person = new Person();
person[0] = "hello";
person[1] = "world";
Console.WriteLine(person[0]);
看起來對象像個數(shù)組一樣,呵呵。



















