索引器(Indexer)#
来源:
D:\study\C#1\stu0728\索引器
索引器允许对象像数组一样通过索引([])来访问。本质是一种特殊的属性,使用 this 关键字定义。
基本语法#
示例:ClassRoom 索引器#
class Student
{
public string Name { get; set; }
public string Sex { get; set; }
}
class ClassRoom
{
public List<Student> students = new List<Student>();
public void Add(Student s)
{
students.Add(s);
}
// 定义索引器 — 使用 int 作为索引
public Student this[int index]
{
get
{
Console.WriteLine("get 方法执行了,索引值:" + index);
return students[index];
}
set
{
Console.WriteLine("set 执行了");
students[index] = value;
}
}
// 索引器重载 — 使用 string 作为索引(按姓名查找)
public Student this[string index]
{
get
{
return students.Find(v => v.Name == index);
}
set
{
// 按姓名设置
}
}
}
使用:
ClassRoom classRoom = new ClassRoom();
classRoom.Add(new Student() { Name = "hhh", Sex = "男" });
// 通过索引器访问
classRoom[0] = new Student() { Name = "123123", Sex = "男" }; // set 执行
Student s = classRoom[0]; // get 执行
索引器 vs 数组#
| 特性 | 数组 | 索引器 |
|---|---|---|
| 索引类型 | 只能是 int |
可以是任意类型(int、string 等) |
| 底层存储 | 连续内存 | 内部可使用 List<T> 等任意集合 |
| 灵活性 | 低 | 高(可自定义查找逻辑) |