索引器 indexer 的使用
索引器让自定义类可以用 [] 语法访问,就像数组或字典一样。它的本质是 this[int index] 这样的语法,通过 get/set 访问器定义。
最常见的例子就是 List<T> 和 Dictionary<K,V>,你其实一直在用索引器。自己写一个 Configuration 类,让 config["ConnectionString"] 就能取值,比 config.Get("...") 直观。
索引器可以重载:int 索引、string 索引、多参数索引都可以。注意不要在索引器里写复杂逻辑,保持简单。
代码示例
public class DataStore
{
private Dictionary<string, string> _data = new();
// string 索引器
public string this[string key]
{
get => _data.TryGetValue(key, out var v) ? v : "";
set => _data[key] = value;
}
// int 索引器(按序号)
public string this[int index]
{
get
{
var keys = _data.Keys.ToList();
return keys[index];
}
}
}
// 使用
var store = new DataStore();
store["username"] = "Tom";
Console.WriteLine(store["username"]); // Tom
store["email"] = "tom@example.com";
Console.WriteLine(store[0]); // 第一个 key
学习小结:以上是我学习这个知识点时的笔记和心得。技术学习没有捷径,多写多练多踩坑,自然就掌握了。如果这篇笔记对你有帮助,欢迎继续看看其他文章。