C#基础知识之this关键字介绍
一、this可以代表引用类的当前实例,包括继承而来的方法,通常可以省略。
publicclassPerson
{
publicstringName{get;set;}
publicintAge{get;set;}
publicPerson(stringName,intAge)
{
this.Age=Age;
this.Name=Name;
}
}
这个不用多说,当对象调用自己内部函数的时候,用到对象使用this即可。
二、this关键字后面跟“:”符号,可以调用其它的构造函数
//声明有实现的构造函数
publicPerson()
{
this.NAge=100;
Console.WriteLine("我是超人!");
}
publicPerson(intnAge)
{
Console.WriteLine("超人的年龄{0}",nAge);
}
//使用this关键字调用了第二个一个参数的构造函数
publicPerson(intnAge,stringstrName)
:this(1)
{
Console.WriteLine("我是叫{0}的超人,年龄{1}",strName,nAge);
}
我们创建该对象看看是否调用成功。在Main函数中添加如下代码:
Personp=newPerson(10,"强子");
执行会输出:
超人的年龄1 我是叫强子的超人,年龄10
三、声明索引器
索引器类型表示该索引器使用哪一类型的索引来存取数组或集合元素,可以是整数,可以是字符串;this表示操作本对象的数组或集合成员,可以简单把它理解成索引器的名字,因此索引器不能具有用户定义的名称。例如:
publicclassPerson
{
string[]PersonList=newstring[10];
publicstringthis[intparam]
{
get{returnPersonList[param];}
set{PersonList[param]=value;}
}
}
其中索引的数据类型必须与索引器的索引类型相同。例如:
Personperson=newPerson(); person[0]="hello"; person[1]="world"; Console.WriteLine(person[0]);
看起来对象像个数组一样,呵呵。
热门推荐
10 广西考试祝福语结婚简短
11 猪年祝福语简短小孩
12 元旦祝福语送长辈简短
13 恭喜二宝祝福语简短
14 祝福语暖心话简短
15 国庆中秋祝福语简短兄弟
16 朋友订婚的祝福语简短
17 送弟弟中秋祝福语简短
18 爱生日祝福语简短独特