C#中的this用法,相信大家应该有用过,但你用过几种?以下是个人总结的this几种用法,欢迎大家拍砖,废话少说,直接列出用法及相关代码。
this用法1:限定被相似的名称隐藏的成员
////// /******************************************/ /// /* this用法1:限定被相似的名称隐藏的成员 */ /// /******************************************/ /// /// public Person(string Name, string Sex) { this.Name = Name; this.Sex = Sex; }
this用法2:将对象作为参数传递到其他方法
//////Person 的摘要说明 /// public class Person { ////// 姓名 /// public string Name { set; get; } ////// /*******************************************/ /// /* this用法2:将对象作为参数传递到其他方法 */ /// /*******************************************/ /// public void ShowName() { Helper.PrintName(this); } } ////// 辅助类 /// public static class Helper { ////// 打印人名 /// /// public static void PrintName(Person person) { HttpContext.Current.Response.Write("姓名:" + person.Name + ""); } }
this用法3:声明索引器
////// 其它属性 /// public NameValueCollection Attr = new NameValueCollection(); ////// /*************************/ /// /* this用法3:声明索引器 */ /// /*************************/ /// /// ///public string this[string key] { set { Attr[key] = value; } get { return Attr[key]; } }
this用法4:扩展对象的方法
//////Person 的摘要说明 /// public class Person { ////// 性别 /// public string Sex { set; get; } } ////// 辅助类 /// public static class Helper { ////// /*****************************/ /// /* this用法4:扩展对象的方法 */ /// /*****************************/ /// /// ///public static string GetSex(this Person item) { return item.Sex; } }调用:Person person = new Person(); person.GetSex();