跳转到内容
主菜单
主菜单
移至侧栏
隐藏
导航
首页
最近更改
随机页面
MediaWiki帮助
代码酷
搜索
搜索
中文(中国大陆)
外观
创建账号
登录
个人工具
创建账号
登录
未登录编辑者的页面
了解详情
贡献
讨论
编辑“︁
C Sharp 索引器
”︁
页面
讨论
大陆简体
阅读
编辑
编辑源代码
查看历史
工具
工具
移至侧栏
隐藏
操作
阅读
编辑
编辑源代码
查看历史
常规
链入页面
相关更改
特殊页面
页面信息
外观
移至侧栏
隐藏
您的更改会在有权核准的用户核准后向读者展示。
警告:
您没有登录。如果您进行任何编辑,您的IP地址会公开展示。如果您
登录
或
创建账号
,您的编辑会以您的用户名署名,此外还有其他益处。
反垃圾检查。
不要
加入这个!
= C#索引器 = 索引器(Indexer)是C#中的一种特殊类成员,允许对象像数组一样通过索引来访问其内部集合或数组中的元素。索引器提供了一种更直观的方式来访问类或结构体中的数据,特别是当类表示某种集合时。 == 简介 == 索引器类似于属性,但使用索引参数而不是名称来访问值。它们通常用于封装数组或集合,使外部代码可以通过类似数组的语法来访问元素,而不必直接暴露内部数据结构。 索引器的语法与属性类似,但使用'''this'''关键字和方括号'''[]'''来定义。索引器可以有多个参数,支持重载,并且可以有不同的访问修饰符。 == 基本语法 == 索引器的基本语法如下: <syntaxhighlight lang="csharp"> public returnType this[indexType index] { get { // 返回索引对应的值 } set { // 设置索引对应的值 } } </syntaxhighlight> * '''returnType''':索引器返回的数据类型。 * '''indexType''':索引参数的类型(通常是int或string)。 * '''get'''和'''set''':定义索引器的读取和写入行为。 === 示例:简单索引器 === 以下是一个封装整数数组的类,通过索引器提供访问: <syntaxhighlight lang="csharp"> 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 </syntaxhighlight> == 多参数索引器 == 索引器可以接受多个参数,例如模拟二维数组或字典: <syntaxhighlight lang="csharp"> 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 </syntaxhighlight> == 字符串索引器 == 索引器的索引类型不限于整数,也可以是字符串或其他类型: <syntaxhighlight lang="csharp"> 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 </syntaxhighlight> == 索引器与属性的区别 == {| class="wikitable" |- ! 特性 !! 索引器 !! 属性 |- | 访问方式 || 通过索引(如obj[0]) || 通过名称(如obj.Property) |- | 参数 || 可以有一个或多个参数 || 无参数 |- | 重载 || 支持重载(不同参数类型或数量) || 不支持重载 |- | 用途 || 通常用于集合类 || 用于封装字段 |} == 实际应用场景 == 索引器在以下场景中非常有用: 1. '''封装集合''':隐藏内部数据结构,提供更简洁的访问方式。 2. '''模拟数组''':使自定义类可以像数组一样使用。 3. '''字典或映射''':通过键快速访问值。 === 案例:自定义集合类 === 以下是一个封装List<T>的类,通过索引器提供访问: <syntaxhighlight lang="csharp"> 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 </syntaxhighlight> === 案例:配置文件访问 === 索引器可以用于简化配置文件的读写: <syntaxhighlight lang="csharp"> 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 </syntaxhighlight> == 高级特性 == === 索引器重载 === 类可以定义多个索引器,只要它们的参数类型或数量不同: <syntaxhighlight lang="csharp"> 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; } } </syntaxhighlight> === 显式接口实现索引器 === 索引器可以显式实现接口: <syntaxhighlight lang="csharp"> 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; } } </syntaxhighlight> == 性能注意事项 == * 索引器的性能与直接访问底层数据结构几乎相同,因为编译器会内联简单的get/set方法。 * 避免在索引器中执行复杂逻辑,以保持访问速度。 == 总结 == 索引器是C#中强大的特性,允许对象以类似数组的方式被访问。它们提高了代码的可读性和封装性,特别适用于集合类或需要自定义访问逻辑的场景。通过合理使用索引器,可以使API更加直观和易于使用。 {{C#高级类特性}} [[Category:编程语言]] [[Category:C Sharp]] [[Category:C Sharp 高级类特性]]
摘要:
请注意,所有对代码酷的贡献均被视为依照知识共享署名-非商业性使用-相同方式共享发表(详情请见
代码酷:著作权
)。如果您不希望您的文字作品被随意编辑和分发传播,请不要在此提交。
您同时也向我们承诺,您提交的内容为您自己所创作,或是复制自公共领域或类似自由来源。
未经许可,请勿提交受著作权保护的作品!
取消
编辑帮助
(在新窗口中打开)
该页面使用的模板:
模板:C
(
编辑
)