c# this关键字的理解

时间:2023-03-09 16:13:34
c# this关键字的理解

this关键字引用类的当前实例

1/限定被相似的名称隐藏的成员

2/将对象作为参数传递到其他方法

3/声明索引器

实际案例参考:

//成员类
public class Employee
{
private string _MyName;
private int _MyAge;
public string[] _arry = new string[]; public string Name { get { return this._MyName; } } public int Age { get {return this._MyAge; } } public Employee(string name, int age)
{
this._MyName = name;
this._MyAge = age;
}
public string this[int param] {
get { return _arry[param]; }
set { _arry[param] = value; }
} public void PrintInfo() {
Print.DoPrint(this);
} //改善C#程序的50种方法
}
//打印类
public class Print {
public static void DoPrint(Employee e)
{
Console.WriteLine("Name:{0}\nAge:{1}",e.Name,e.Age);
} }

执行代码 和结果

 Employee emp = new ConsoleApplication5.Employee("Zmztya",);
//打印本人信息
emp.PrintInfo();
emp[] = "Father";
emp[] = "Mather";
emp[] = "Sister";
for (int i = ; i < ; i++)
{
Console.WriteLine("家庭成员:{0}",emp[i]);
}
Console.WriteLine(); 结果: Name:Zmztya Age:
家庭成员:father
....(省略其他四个,最后两个是空值)

this 的关键字并没有发现其他特殊的用法。可以去掉除索引的意外的this,效果是一样的。