以中括号得形式范围自定义类中元素,访问时和数组一样
适用于类中有数组时使用
写法:访问修饰符 返回值 this[参数列表]
get和set
可以重载
结构体也支持索引器
using System;
namespace Lesson6_封装_索引器
{
class Person
{
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;
}
}
public string this[string str]
{
get
{
return name;
}
}
public Person this[int index]
{
get
{
if (friends == null)
{
return null;
}
else if (friends.Length - 1 < index)
{
return null;
}
return friends[index];
}
set
{
if (friends == null)
{
friends = new Person[] { value };
}
else if (index > friends.Length - 1)
{
friends[friends.Length - 1] = value;
}
friends[index] = value;
}
}
}
class Program
{
static void Main(string[] args)
{
Person p = new Person();
p[0] = new Person();
Console.WriteLine(p[0]);
}
}
}