欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#基礎(chǔ)知識(shí)之this關(guān)鍵字介紹

 更新時(shí)間:2016年04月23日 16:03:33   作者:Swich  
本文主要介紹this關(guān)鍵字的幾種使用方法,this可以代表當(dāng)前實(shí)例,可以調(diào)用其他構(gòu)造函數(shù),還可以用來(lái)構(gòu)建索引器,這里都有一一舉例說(shuō)明。

一、this可以代表引用類的當(dāng)前實(shí)例,包括繼承而來(lái)的方法,通常可以省略。

復(fù)制代碼 代碼如下:

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;
    }
}

這個(gè)不用多說(shuō),當(dāng)對(duì)象調(diào)用自己內(nèi)部函數(shù)的時(shí)候,用到對(duì)象使用this即可。

二、this關(guān)鍵字后面跟“:”符號(hào),可以調(diào)用其它的構(gòu)造函數(shù)

復(fù)制代碼 代碼如下:

//聲明有實(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)用了第二個(gè)一個(gè)參數(shù)的構(gòu)造函數(shù)
public Person(int nAge, string strName)
    : this(1)
{
    Console.WriteLine("我是叫{0}的超人,年齡{1}", strName, nAge);
}

我們創(chuàng)建該對(duì)象看看是否調(diào)用成功。在Main函數(shù)中添加如下代碼:

復(fù)制代碼 代碼如下:
Person p = new Person(10,"強(qiáng)子");

執(zhí)行會(huì)輸出:

復(fù)制代碼 代碼如下:

超人的年齡1
我是叫強(qiáng)子的超人,年齡10

三、聲明索引器

索引器類型表示該索引器使用哪一類型的索引來(lái)存取數(shù)組或集合元素,可以是整數(shù),可以是字符串;this表示操作本對(duì)象的數(shù)組或集合成員,可以簡(jiǎn)單把它理解成索引器的名字,因此索引器不能具有用戶定義的名稱。例如:

復(fù)制代碼 代碼如下:

public class Person
{
    string[] PersonList = new string[10];
    public string this[int param]
    {
        get { return PersonList[param]; }
        set { PersonList[param] = value; }
    }
}

其中索引的數(shù)據(jù)類型必須與索引器的索引類型相同。例如:

復(fù)制代碼 代碼如下:

Person person = new Person();
person[0] = "hello";
person[1] = "world";
Console.WriteLine(person[0]);

看起來(lái)對(duì)象像個(gè)數(shù)組一樣,呵呵。

相關(guān)文章

最新評(píng)論