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集合中查询数据

 

转载于:https://www.cnblogs.com/sggggr/articles/7944695.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值