C# 索引器(Indexer)
C# 索引器(Indexer) 是一种特殊的属性(Property),使你可以像访问数组一样通过 [] 操作符访问对象的内部数据。这在自定义集合类、封装多维数据、表达语义化访问方式时非常有用。
1. 索引器语法与基本概念
public class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get => arr[i];
set => arr[i] = value;
}
}
✅ 说明:
this[int i]:索引器声明,int是索引类型,可以自定义(例如string,enum, 多个参数等)。get/set:访问或修改索引对应的数据。
2. 实战示例:自定义字符串字典访问
public class StringDictionary
{
private Dictionary<string, string> data = new();
public string this[string key]
{
get => data.ContainsKey(key) ? data[key] : null;
set => data[key] = value;
}
}
✅ 用法示例:
var dict = new StringDictionary();
dict["Name"] = "ChatGPT";
Console.WriteLine(dict["Name"]); // 输出:ChatGPT
3. 多参数索引器
你可以定义多个索引参数,类似二维数组的访问方式:
public class Matrix
{
private int[,] data = new int[10, 10];
public int this[int x, int y]
{
get => data[x, y];
set => data[x, y] = value;
}
}
✅ 使用:
var m = new Matrix();
m[1, 2] = 42;
Console.WriteLine(m[1, 2]); // 输出 42
4. 使用索引器增强集合类封装
public class BookShelf
{
private List<string> books = new();
public string this[int index]
{
get => books[index];
set => books[index] = value;
}
public void Add(string book) => books.Add(book);
}
✅ 使用:
var shelf = new BookShelf();
shelf.Add("C# Basics");
shelf.Add("Advanced C#");
Console.WriteLine(shelf[1]); // 输出:Advanced C#
5. 与属性的区别对比
| 特性 | 属性(Property) | 索引器(Indexer) |
|---|---|---|
| 语法 | 通过名称访问 | 通过 [] 访问 |
| 名称 | 有名称(如 Name) | 没有名称,始终是 this |
| 应用场景 | 控制单个值的访问逻辑 | 控制集合中多个值的访问逻辑 |
| 可索引类型 | ❌ 一般不可通过索引访问 | ✅ 支持 int, string 等索引 |
6. 接口 + 索引器(典型应用)
.NET 中 IList<T> 和 IDictionary<TKey, TValue> 就用到了索引器:
public interface IList<T> : ICollection<T>
{
T this[int index] { get; set; }
}
public interface IDictionary<TKey, TValue> : ICollection<KeyValuePair<TKey, TValue>>
{
TValue this[TKey key] { get; set; }
}
7. 注意事项与限制
- 索引器不能为静态。
- 支持重载(通过不同参数数量或类型)。
- 索引器本质上是语法糖,仍然通过
get和set方法执行。
📚 权威参考
- Microsoft 官方文档:
🔗 C# Indexers – Microsoft Learn
更多详细内容请关注其他相关文章!