本文主要介绍this关键字的几种使用方法,this可以代表当前实例,可以调用其他构造函数,还可以用来构建索引器,这里都有一一举例说明。
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string Name, int Age)
{
this.Age = Age;
this.Name = Name;
}
}
//声明有实现的构造函数
public Person()
{
this.NAge = 100;
Console.WriteLine("我是超人!");
}
public Person(int nAge)
{
Console.WriteLine("超人的年龄{0}", nAge);
}
//使用this关键字调用了第二个一个参数的构造函数
public Person(int nAge, string strName)
: this(1)
{
Console.WriteLine("我是叫{0}的超人,年龄{1}", strName, nAge);
}
超人的年龄1
我是叫强子的超人,年龄10
一、this可以代表引用类的当前实例,包括继承而来的方法,通常可以省略。
复制代码
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string Name, int Age)
{
this.Age = Age;
this.Name = Name;
}
}
这个不用多说,当对象调用自己内部函数的时候,用到对象使用this即可。
二、this关键字后面跟“:”符号,可以调用其它的构造函数
复制代码
//声明有实现的构造函数
public Person()
{
this.NAge = 100;
Console.WriteLine("我是超人!");
}
public Person(int nAge)
{
Console.WriteLine("超人的年龄{0}", nAge);
}
//使用this关键字调用了第二个一个参数的构造函数
public Person(int nAge, string strName)
: this(1)
{
Console.WriteLine("我是叫{0}的超人,年龄{1}", strName, nAge);
}
我们创建该对象看看是否调用成功。在Main函数中添加如下代码:
复制代码 Person p = new Person(10,"强子");
执行会输出:
复制代码
超人的年龄1
我是叫强子的超人,年龄10
三、声明索引器
索引器类型表示该索引器使用哪一类型的索引来存取数组或集合元素,可以是整数,可以是字符串;this表示操作本对象的数组或集合成员,可以简单把它理解成索引器的名字,因此索引器不能具有用户定义的名称。例如:










