C#中This用法的简单小例子

总结了一些This的理解和例子

using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Threading.Tasks;


namespace GouZaoHanShu
{
    class Program
    {
        static void Main(string[] args)
        {
            TestThis B=new TestThis("Male");
        }
    }//endclassprogram

    class TestThis
    {
        string name="Mary";//全局变量的name
        string ages{get;set;}
        public TestThis(string name,int age)//局部变量的name
        {
            name = this.name;/*在一个函数中,使用了一个和全局变量一样名字的局部变量,
                               如果 前面不加This就表示局部变量(就近原则),加了This表示全局变量
                              */
            Console.WriteLine("My name is  "+name+"and I'm "+age+" years old!");
        }
        public TestThis(string gender) :this("leo",100)//this 指代一个构造函数,具体是哪一个要看重载的参数来决定           
        {                                                //这个构造函数执行的时候,首先执行this指代的构造函数
            Console.WriteLine("My gender is "+gender);
        }
    }//endclassTestThis
}//end namespace
/*总结:this有三个个作用:1.当局部变量和全局变量重名的时候,变量前面加上this表示全局变量(当然,在局部使用这种重名变量的时候加This才有意义)

                           2.:this()可以用来指代某个构造函数,括号的参数决定是哪一个重载

                          3.this指代当前所在的函数中,如:

public class TestThreading
    {
        private System.Object lockThis = new System.Object();
        
        public void Process()
        {
            
            lock (lockThis)
            {
                // Access thread-sensitive resources.
            }
        }
        
    }

 */


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Unity3d青子

难题的解决使成本节约,求打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值