C# this关键字的四种用法(转载)

用法一  this代表当前类的实例对象

 1 namespace Demo
 2 {
 3     public class Test
 4     {
 5         private string scope = "全局变量";
 6         public string getResult()
 7         {
 8             string scope = "局部变量";
 9        // this代表Test的实例对象
10        // 所以this.scope对应的是全局变量
11         // scope对应的是getResult方法内的局部变量
12             return this.scope + "-" + scope;
13         }
14     }
15 
16     class Program
17     {
18         static void Main(string[] args)
19         {
20             try
21             {
22                 Test test = new Test();
23                 Console.WriteLine(test.getResult());
24             }
25             catch (Exception ex)
26             {
27                 Console.WriteLine(ex);
28             }
29             finally
30             {
31                 Console.ReadLine();
32             }
33 
34         }
35     }
36 }

用法二  用this串联构造函数

 1 namespace Demo
 2 {
 3     public class Test
 4     {
 5         public Test()
 6         {
 7             Console.WriteLine("无参构造函数");
 8         }
 9         // this()对应无参构造方法Test()
10      // 先执行Test(),后执行Test(string text)
11         public Test(string text) : this()
12         {
13             Console.WriteLine(text);
14             Console.WriteLine("有参构造函数");
15         }
16     }
17 
18     class Program
19     {
20         static void Main(string[] args)
21         {
22             try
23             {
24                 Test test = new Test("张三");
25             }
26             catch (Exception ex)
27             {
28                 Console.WriteLine(ex);
29             }
30             finally
31             {
32                 Console.ReadLine();
33             }
34         }
35     }
36 }

输出是:无参构造函数

              张三

              有参构造函数

用法三  为原始类型扩展方法

用法四  索引器(基于索引器封装EPList,用于优化大数据下频发的Linq查询引发的程序性能问题,通过索引从list集合中查询数据

 

posted @ 2017-12-01 22:30  sgggr  阅读(134)  评论(0)    收藏  举报