C Sharp 索引器
外观
C#索引器[编辑 | 编辑源代码]
索引器(Indexer)是C#中的一种特殊类成员,允许对象像数组一样通过索引来访问其内部集合或数组中的元素。索引器提供了一种更直观的方式来访问类或结构体中的数据,特别是当类表示某种集合时。
简介[编辑 | 编辑源代码]
索引器类似于属性,但使用索引参数而不是名称来访问值。它们通常用于封装数组或集合,使外部代码可以通过类似数组的语法来访问元素,而不必直接暴露内部数据结构。
索引器的语法与属性类似,但使用this关键字和方括号[]来定义。索引器可以有多个参数,支持重载,并且可以有不同的访问修饰符。
基本语法[编辑 | 编辑源代码]
索引器的基本语法如下:
public returnType this[indexType index]
{
get
{
// 返回索引对应的值
}
set
{
// 设置索引对应的值
}
}
- returnType:索引器返回的数据类型。
- indexType:索引参数的类型(通常是int或string)。
- get和set:定义索引器的读取和写入行为。
示例:简单索引器[编辑 | 编辑源代码]
以下是一个封装整数数组的类,通过索引器提供访问:
class IntArrayWrapper
{
private int[] array = new int[10];
public int this[int index]
{
get
{
if (index < 0 || index >= array.Length)
throw new IndexOutOfRangeException();
return array[index];
}
set
{
if (index < 0 || index >= array.Length)
throw new IndexOutOfRangeException();
array[index] = value;
}
}
}
// 使用示例
IntArrayWrapper wrapper = new IntArrayWrapper();
wrapper[0] = 42; // 设置值
Console.WriteLine(wrapper[0]); // 输出: 42
多参数索引器[编辑 | 编辑源代码]
索引器可以接受多个参数,例如模拟二维数组或字典:
class Matrix
{
private int[,] data = new int[10, 10];
public int this[int row, int col]
{
get => data[row, col];
set => data[row, col] = value;
}
}
// 使用示例
Matrix matrix = new Matrix();
matrix[2, 3] = 5; // 设置值
Console.WriteLine(matrix[2, 3]); // 输出: 5
字符串索引器[编辑 | 编辑源代码]
索引器的索引类型不限于整数,也可以是字符串或其他类型:
class StringIndexer
{
private Dictionary<string, string> data = new Dictionary<string, string>();
public string this[string key]
{
get => data.ContainsKey(key) ? data[key] : null;
set => data[key] = value;
}
}
// 使用示例
StringIndexer indexer = new StringIndexer();
indexer["name"] = "Alice"; // 设置值
Console.WriteLine(indexer["name"]); // 输出: Alice
索引器与属性的区别[编辑 | 编辑源代码]
特性 | 索引器 | 属性 |
---|---|---|
访问方式 | 通过索引(如obj[0]) | 通过名称(如obj.Property) |
参数 | 可以有一个或多个参数 | 无参数 |
重载 | 支持重载(不同参数类型或数量) | 不支持重载 |
用途 | 通常用于集合类 | 用于封装字段 |
实际应用场景[编辑 | 编辑源代码]
索引器在以下场景中非常有用: 1. 封装集合:隐藏内部数据结构,提供更简洁的访问方式。 2. 模拟数组:使自定义类可以像数组一样使用。 3. 字典或映射:通过键快速访问值。
案例:自定义集合类[编辑 | 编辑源代码]
以下是一个封装List<T>的类,通过索引器提供访问:
class CustomCollection<T>
{
private List<T> items = new List<T>();
public T this[int index]
{
get => items[index];
set => items[index] = value;
}
public void Add(T item) => items.Add(item);
}
// 使用示例
CustomCollection<string> collection = new CustomCollection<string>();
collection.Add("Apple");
collection.Add("Banana");
Console.WriteLine(collection[0]); // 输出: Apple
案例:配置文件访问[编辑 | 编辑源代码]
索引器可以用于简化配置文件的读写:
class ConfigManager
{
private Dictionary<string, string> settings = new Dictionary<string, string>();
public string this[string key]
{
get => settings.ContainsKey(key) ? settings[key] : null;
set => settings[key] = value;
}
}
// 使用示例
ConfigManager config = new ConfigManager();
config["Theme"] = "Dark";
Console.WriteLine(config["Theme"]); // 输出: Dark
高级特性[编辑 | 编辑源代码]
索引器重载[编辑 | 编辑源代码]
类可以定义多个索引器,只要它们的参数类型或数量不同:
class MultiIndexer
{
private int[] array = new int[10];
private Dictionary<string, int> dict = new Dictionary<string, int>();
public int this[int index]
{
get => array[index];
set => array[index] = value;
}
public int this[string key]
{
get => dict.ContainsKey(key) ? dict[key] : -1;
set => dict[key] = value;
}
}
显式接口实现索引器[编辑 | 编辑源代码]
索引器可以显式实现接口:
interface IArrayContainer
{
int this[int index] { get; set; }
}
class ExplicitIndexer : IArrayContainer
{
private int[] array = new int[10];
int IArrayContainer.this[int index]
{
get => array[index];
set => array[index] = value;
}
}
性能注意事项[编辑 | 编辑源代码]
- 索引器的性能与直接访问底层数据结构几乎相同,因为编译器会内联简单的get/set方法。
- 避免在索引器中执行复杂逻辑,以保持访问速度。
总结[编辑 | 编辑源代码]
索引器是C#中强大的特性,允许对象以类似数组的方式被访问。它们提高了代码的可读性和封装性,特别适用于集合类或需要自定义访问逻辑的场景。通过合理使用索引器,可以使API更加直观和易于使用。