C#中this的使用實例分析
this關(guān)鍵字在C#程序設(shè)計中的應(yīng)用非常頻繁,今天本文就this關(guān)鍵字的用法做一番分析,希望能提對大家的C#程序設(shè)計有一定的幫助作用。具體分析如下:
1.代表當前類,在當前類中可使用this訪問當前類成員變量和方法(需要注意的是 靜態(tài)方法中不能使用this),也可用于參數(shù)傳遞,傳遞當前對象的引用。
示例代碼如下:
class Program { static void Main(string[] args) { thisClass testObj = new thisClass(); Console.ReadLine(); } } class thisClass { private string A { get; set; } public thisClass() { /*當前類this 訪問類中屬性A 靜態(tài)方法無法訪問A屬性*/ this.A = "Test String"; Console.WriteLine(this.TestFun("TestFun :")); } private string TestFun(string args) { return args + this.A; } }
運行結(jié)果如下圖所示:
2.聲明索引器
索引器:允許類和結(jié)構(gòu)的實例按照與數(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 索引可以被重載,屬于實例成員,不能聲明為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) { /*當前類this 訪問類中屬性A 靜態(tài)方法無法訪問A屬性*/ this.A = str; Console.WriteLine(this.TestFun("TestFun :")); } private string TestFun(string args) { return args + this.A; } }
運行結(jié)果如下圖所示:
相關(guān)文章
總結(jié)C#刪除字符串數(shù)組中空字符串的幾種方法
C#中要如何才能刪除一個字符串數(shù)組中的空字符串呢?下面的文章會介紹多種方式來實現(xiàn)清除數(shù)組中的空字符串,以及在.net中將字符串數(shù)組中字符串為空的元素去除。2016-08-08C#實現(xiàn)百分比轉(zhuǎn)小數(shù)的方法
這篇文章主要介紹了C#實現(xiàn)百分比轉(zhuǎn)小數(shù)的方法,涉及C#進行數(shù)值計算的相關(guān)技巧,需要的朋友可以參考下2015-06-06C# 中const,readonly,static的使用小結(jié)
這篇文章主要介紹了C# 中使用const,readonly,static的示例,幫助大家更好的理解和使用c#,感興趣的朋友可以了解下2021-01-01