如果想从外边访问类的私有成员变量,除了增加public属性外,可以通过索引器来访问。
格式:public 返回类型 this [ 索引类型 变量]
如果索引器中返回的类型不一致时,可以用object作为返回类型。代码如下:
class Person
{
private int _age;
private string _name;
public object this[int index]
{
get
{
if (index == 0)
{
return _age;
}
else
{
return _name;
}
}
set
{
if (index == 0)
{
_age = Convert.ToInt32(value);
}
else
{
_name = value.ToString();
}
}
}
}
索引器可以重载。
this索引器被编译器解释成类型为索引器返回类型,名为“Item”的属性,也就是说如果在类中定义”public object Item”的属性,编译器会报错。