C#-索引器
概念
索引器(Indexer) 允许类中的对象可以像数组那样方便、直观的被引用。当为类定义一个索引器时,该类的行为就会像一个 虚拟数组(virtual array) 一样。
索引器可以有参数列表,且只能作用在实例对象上,而不能在类上直接作用。
可以使用数组访问运算符([ ])来访问该类的实例。
索引器的行为的声明在某种程度上类似于属性(property)。属性可使用 get 和 set 访问器来定义索引器。但是属性返回或设置的是一个特定的数据成员,而索引器返回或设置对象实例的一个特定值。
定义一个一维数组的索引器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | element-type this [ int index] { // get 访问器 get { // 返回 index 指定的值 } // set 访问器 set { // 设置 index 指定的值 } } |
提示:索引器必须以this关键字定义,this 是类实例化之后的对象
实例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | using System; namespace C_Pro { public class Student { private string name; private string grade; public string Name { get { return name; } set {name = value; } } public string Grade { get { return grade; } set {grade = value; } } // 定义索引器 public string this [ int index] { get { if (index == 0) return name; else if (index == 1) return grade; else return null ; } set { if (index == 0) name = value; else if (index == 1) grade = value; } } static void Main( string [] args) { Student s = new Student(); s[0] = "Jeson" ; s[1] = "First-year" ; Console.WriteLine(s.Name); Console.WriteLine(s.Grade); Console.ReadKey(); } } } |
运行后结果:
1 2 3 | Jeson First-year |
重载索引器
索引器(Indexer)可被重载。索引器声明的时候也可带有多个参数,且每个参数可以是不同的类型。没有必要让索引器必须是整型的。C# 允许索引器可以是其他类型,例如,字符串类型。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | using System; namespace C_Pro { public class IndexedNames { private string [] namelist = { "a" , "b" , "c" , "d" }; // 输入namelist的index返回对应的值 public string this [ int index] { get { return namelist[index]; } set { namelist[index] = value; } } // 输入namelist的值,返回对应的索引 public int this [ string name] { get { for ( int i=0; i<namelist.Length; i++) { if (namelist[i] == name) return i; } return -1; } } static void Main( string [] args) { IndexedNames name = new IndexedNames(); Console.WriteLine(name[1]); Console.WriteLine(name[ "a" ]); } } } |
运行后结果:
1 2 | b 0 |
索引器与数组的区别:
- 索引器的索引值(Index)类型不限定为整数,用来访问数组的索引值(Index)一定为整数,而索引器的索引值类型可以定义为其他类型。
- 索引器允许重载, 一个类不限定为只能定义一个索引器,只要索引器的函数签名不同,就可以定义多个索引器,可以重载它的功能。
- 索引器不是一个变量,索引器没有直接定义数据存储的地方,而数组有。索引器具有Get和Set访问器。
索引器与属性的区别:
- 索引器以函数签名方式 this 来标识,而属性采用名称来标识,名称可以任意。
- 索引器可以重载,而属性不能重载。
- 索引器不能用static 来进行声明,而属性可以。索引器永远属于实例成员,因此不能声明为static。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 【.NET】调用本地 Deepseek 模型
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库