this关键字的四种作用

1. 在类中使用,表示类的实例对象。

    public class Test
    {
        private string scope = "类的字段";
        public string getResult()
        {
            string scope = "局部变量";
        // this.scope = "类的字段"  scope = "局部变量"
            return this.scope + "-" + scope;
        }
    }

2. 串联构造函数。(一个构造函数调用其他构造函数)

using System;

public class Person
{
	public Person()
	{
		Console.WriteLine("无参构造函数");
	}
	// this()对应无参构造方法Person()
	// 先执行Person(),后执行Person(string name)
	public Person(string name) : this()
	{
		//无法通过这种方式实现,Cannot assign to `this' because it is read-only
		//this = new Person();	
		//无法通过这种方式实现,因为new出来的Person并不是this
		//new Person();
		Console.WriteLine("create person, name:{0}", name);
		Console.WriteLine("有参构造函数");
	}
}
class Program
{
    static void Main(string[] args)
    {
        Person zhangsan = new Person("张三");
    }
}

3. 添加扩展方法。

4. 索引器。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值