索引器是一类共对象在外部以一种更便捷的方式访问或修改类内变量的方法,例如:依据索引访问类内集合性质的元素以及其他更加自由的操作。在语法上,综合了函数与成员属性的写法。允许重载。其内部的get/set规则也与成员属性类似。
cs
namespace ConsoleApp5
{
class Person
{
public Person()
{
array = new int[10, 10]; // 或根据需要设定维度
}
private string name;
private int age;
private Person[] friends;
private int[,] array;
//利用索引器访问二维数组
public int this[int i, int j]
{
get { return array[i, j]; }
set { array[i, j] = value; }
}
//利用索引器传入的字符串返回对应的成员变量
private string this[string str]
{
get
{
switch (str)
{
case "name":
return this.name;
break;
case "age":
return this.age.ToString();
default:
return "";
}
}
}
//利用索引器访问一维数组(允许添加额外逻辑)
public Person this[int index]
{
get
{
if (friends == null || friends.Length - 1 < index)
{
return null;
}
else
{
return friends[index];
}
}
set
{
if (friends == null)
{
friends = new Person[] { value };
}
else if (friends.Length - 1 < index)
{
friends[friends.Length - 1] = value;
}
else
{
friends[index] = value;
}
}
}
}
class Program
{
static void Main(string[] args)
{
Person p = new Person();
p[0] = new Person();
Console.WriteLine(p[0]);
p[0, 0] = 10;
}
}
}