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. 索引器。

你可能感兴趣的:(C#语法)