如有錯誤,歡迎指正。
1.代表當前類,在當前類中可使用this訪問當前類成員變量和方法(需要注意的是 靜態方法中不能使用this),也可用于參數傳遞,傳遞當前對象的引用。
下面貼代碼:
class PRogram { static void Main(string[] args) { thisClass testObj = new thisClass(); Console.ReadLine(); } } class thisClass { private string A { get; set; } public thisClass() { /*當前類this 訪問類中屬性A 靜態方法無法訪問A屬性*/ this.A = "Test String"; Console.WriteLine(this.TestFun("TestFun :")); } private string TestFun(string args) { return args + this.A; } }
2.聲明索引器
索引器:允許類和結構的實例按照與數組相同的方式進行索引,索引器類似與屬性,不同之處在于他們的訪問器采用參數,被稱為有參屬性,索引可以被重載,屬于實例成員,不能聲明為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(); /*創建索引器1 索引可以被重載,屬于實例成員,不能聲明為static*/ public thisClass this[int index] { get { return thisClassArr[index]; } set { this.thisClassArr[index] = value; } } /*創建索引器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 靜態方法無法訪問A屬性*/ this.A = str; Console.WriteLine(this.TestFun("TestFun :")); } private string TestFun(string args) { return args + this.A; } }
3.用于擴展方法
擴展方法的要素:1.此方法必須是一個靜態方法2.此方法必須放在靜態類中3.此方法的第一個參數必須以this開頭,并且指定此方法是擴展自哪個類型
public static string DateToString(this DateTime dt){ return dt.ToString("yyyy-mm-dd hh:mm:ss");} static void Main(string[] args){ DateTime now = DateTime.Now; string time = now.DateToString(); Console.WriteLine(time); Console.ReadKey();}
我看了好像就這么多,其他還有補充的沒?
新聞熱點
疑難解答