C#中的this用法,相信你們應該有用過,但你用過幾種?如下是我的總結的this幾種用法,歡迎你們拍磚,廢話少說,直接列出用法及相關代碼。this
this用法1:限定被類似的名稱隱藏的成員spa
/// <summary> /// /******************************************/ /// /* this用法1:限定被類似的名稱隱藏的成員 */ /// /******************************************/ /// </summary> /// <param name="Name"></param> public Person(string Name, string Sex) { this.Name = Name; this.Sex = Sex; }
this用法2:將對象做爲參數傳遞到其餘方法code
/// <summary> ///Person 的摘要說明 /// </summary> public class Person { /// <summary> /// 姓名 /// </summary> public string Name { set; get; } /// <summary> /// /*******************************************/ /// /* this用法2:將對象做爲參數傳遞到其餘方法 */ /// /*******************************************/ /// </summary> public void ShowName() { Helper.PrintName(this); } } /// <summary> /// 輔助類 /// </summary> public static class Helper { /// <summary> /// 打印人名 /// </summary> /// <param name="person"></param> public static void PrintName(Person person) { HttpContext.Current.Response.Write("姓名:" + person.Name + "<br />"); } }
this用法3:聲明索引器對象
/// <summary> /// 其它屬性 /// </summary> public NameValueCollection Attr = new NameValueCollection(); /// <summary> /// /*************************/ /// /* this用法3:聲明索引器 */ /// /*************************/ /// </summary> /// <param name="key"></param> /// <returns></returns> public string this[string key] { set { Attr[key] = value; } get { return Attr[key]; } }
this用法4:擴展對象的方法blog
/// <summary> ///Person 的摘要說明 /// </summary> public class Person { /// <summary> /// 性別 /// </summary> public string Sex { set; get; } } /// <summary> /// 輔助類 /// </summary> public static class Helper { /// <summary> /// /*****************************/ /// /* this用法4:擴展對象的方法 */ /// /*****************************/ /// </summary> /// <param name="item"></param> /// <returns></returns> public static string GetSex(this Person item) { return item.Sex; } } 調用: Person person = new Person(); person.GetSex();