概念
Indexers allow instances of a class or struct to be indexed just like arrays. The indexed value can be set or retrieved without explicitly specifying a type or instance member. Indexers resemble properties except that their accessors take parameters.
索引器允许一个类或结构体的实例可以像数组一样通过下标的形式来访问;
索引器类似属性,不同之处是它的访问器需要参数
语法
定义:
访问修饰符和返回类型
public returnType this[indexType index]
{
get
{
// 返回索引对应的值
}
set
{
// 设置索引对应的值
}
}
用法:
public class StringCollection
{
private List<string> data = new List<string>();
public string this[int index]
{
get
{
return data[index];
}
set
{
data[index] = value;
}
}
public int Count
{
get { return data.Count; }
}
public void Add(string item)
{
data.Add(item);
}
}
// 使用索引器访问 StringCollection 实例
StringCollection collection = new StringCollection();
collection.Add("Hello");
collection.Add("World");
Console.WriteLine(collection[0]); // 输出: Hello
Console.WriteLine(collection[1]); // 输出: World
class MapManager: Singleton<MapManager>
{
//管理器字典
Dictionary<int, Map> Maps = new Dictionary<int, Map>();
//索引器
public Map this[int index]
{
get
{
return this.Maps[index];
}
set
{
this.Maps[index] = value;
}
}
}
多维索引器
public class Matrix
{
private int[,] data;
public Matrix(int rows, int columns)
{
data = new int[rows, columns];
}
public int this[int row, int column]
{
get { return data[row, column]; }
set { data[row, column] = value; }
}
}
重载索引器
类可以定义多个索引器,每个索引器可以接受不同数量和类型的索引参数。这使得可以根据不同的条件重载索引器,从而提供更灵活的访问方式。
public class Data
{
private List<string> items;
public Data()
{
items = new List<string>();
}
public string this[int index]
{
get { return items[index]; }
set { items[index] = value; }
}
public string this[string key]
{
get { return items.FirstOrDefault(item => item.StartsWith(key)); }
}
}
接口索引器与类索引器
- 接口索引器不使用访问修饰符
- 接口索引器通常没有正文
// 定义一个接口,包含一个索引器
public interface IIndexerInterface
{
// 索引器声明
string this[int index] { get; set; }
}
// 实现接口的类
public class IndexerClass : IIndexerInterface
{
private string[] data = new string[10]; // 内部数据
// 实现接口中的索引器
public string this[int index]
{
get
{
// 返回索引对应的数据
return data[index];
}
set
{
// 设置索引对应的数据
data[index] = value;
}
}
}