C#中this的使用實(shí)例分析
this關(guān)鍵字在C#程序設(shè)計(jì)中的應(yīng)用非常頻繁,今天本文就this關(guān)鍵字的用法做一番分析,希望能提對(duì)大家的C#程序設(shè)計(jì)有一定的幫助作用。具體分析如下:
1.代表當(dāng)前類,在當(dāng)前類中可使用this訪問當(dāng)前類成員變量和方法(需要注意的是 靜態(tài)方法中不能使用this),也可用于參數(shù)傳遞,傳遞當(dāng)前對(duì)象的引用。
示例代碼如下:
class Program { static void Main(string[] args) { thisClass testObj = new thisClass(); Console.ReadLine(); } } class thisClass { private string A { get; set; } public thisClass() { /*當(dāng)前類this 訪問類中屬性A 靜態(tài)方法無法訪問A屬性*/ this.A = "Test String"; Console.WriteLine(this.TestFun("TestFun :")); } private string TestFun(string args) { return args + this.A; } }
運(yùn)行結(jié)果如下圖所示:
2.聲明索引器
索引器:允許類和結(jié)構(gòu)的實(shí)例按照與數(shù)組相同的方式進(jìn)行索引,索引器類似與屬性,不同之處在于他們的訪問器采用參數(shù),被稱為有參屬性,索引可以被重載,屬于實(shí)例成員,不能聲明為static。
示例代碼如下:
class Program { static void Main(string[] args) { indexClass intIndexClass = new indexClass(); intIndexClass[0] = new thisClass("intIndexClass 111"); intIndexClass[1] = new thisClass("intIndexClass 222"); indexClass stringIndexClass = new indexClass(); stringIndexClass["string1"] = new thisClass("stringIndexClass string1"); stringIndexClass["string2"] = new thisClass("stringIndexClass string2"); Console.ReadLine(); } } class indexClass { /*聲明屬性*/ private thisClass[] thisClassArr = new thisClass[10]; private Hashtable thisClassStrArr = new Hashtable(); /*創(chuàng)建索引器1 索引可以被重載,屬于實(shí)例成員,不能聲明為static*/ public thisClass this[int index] { get { return thisClassArr[index]; } set { this.thisClassArr[index] = value; } } /*創(chuàng)建索引器2*/ public thisClass this[string index] { get { return thisClassStrArr[index] as thisClass; } set { this.thisClassStrArr[index] = value; } } } class thisClass { private string A { get; set; } public thisClass(string str) { /*當(dāng)前類this 訪問類中屬性A 靜態(tài)方法無法訪問A屬性*/ this.A = str; Console.WriteLine(this.TestFun("TestFun :")); } private string TestFun(string args) { return args + this.A; } }
運(yùn)行結(jié)果如下圖所示:
相關(guān)文章
詳解WPF如何動(dòng)態(tài)生成DataGrid的行和列
在日常開發(fā)中,DataGrid作為二維表格,非常適合數(shù)據(jù)的展示和統(tǒng)計(jì),本文以一些簡(jiǎn)單的小例子,簡(jiǎn)述在WPF開發(fā)中,如何動(dòng)態(tài)生成DataGrid的行和列,需要的可以了解下2024-02-02總結(jié)C#刪除字符串?dāng)?shù)組中空字符串的幾種方法
C#中要如何才能刪除一個(gè)字符串?dāng)?shù)組中的空字符串呢?下面的文章會(huì)介紹多種方式來實(shí)現(xiàn)清除數(shù)組中的空字符串,以及在.net中將字符串?dāng)?shù)組中字符串為空的元素去除。2016-08-08C#實(shí)現(xiàn)百分比轉(zhuǎn)小數(shù)的方法
這篇文章主要介紹了C#實(shí)現(xiàn)百分比轉(zhuǎn)小數(shù)的方法,涉及C#進(jìn)行數(shù)值計(jì)算的相關(guān)技巧,需要的朋友可以參考下2015-06-06Unity3D實(shí)現(xiàn)虛擬按鈕控制人物移動(dòng)效果
這篇文章主要為大家詳細(xì)介紹了Unity3D實(shí)現(xiàn)虛擬按鈕控制人物移動(dòng)效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-02-02C# 中const,readonly,static的使用小結(jié)
這篇文章主要介紹了C# 中使用const,readonly,static的示例,幫助大家更好的理解和使用c#,感興趣的朋友可以了解下2021-01-01