// 声明索引器
public string this[int param]
{
get { return _arr[param]; }
set { _arr[param] = value; }
}
}
class Print
{
public static void DoPrint(Employee e)
{
Console.WriteLine("Name: {0}\nAge: {1}", e.Name, e.Age);
}
}
class TestApp
{
static void Main()
{
Employee E = new Employee("Hunts", 21);
E[0] = "Scott";
E[1] = "Leigh";
E[4] = "Kiwis";
E.PrintEmployee();
for(int i=0; i<5; i )
{
Console.WriteLine("Friends Name: {0}", E[i]);
}
Console.ReadLine();
}
}
/**//*
控制台输出:
Name: Hunts
Age: 21
Friends Name: Scott
Friends Name: Leigh
Friends Name:
Friends Name:
Friends Name: Kiwis
*/
注重点
由于静态成员函数存在于类一级,并且不是对象的一部分,因此没有 this 指针。在静态方法中引用 this 是错误的。
索引器答应类或结构的实例按照与数组相同的方式进行索引。索引器类似于属性,不同之处在于它们的访问器采用参数。
评论加载中…
![]() |