C#中,索引器的作用和用法有文件示例最好

来源:学生作业帮助网 编辑:作业帮 时间:2024/05/09 10:46:00
C#中,索引器的作用和用法有文件示例最好

C#中,索引器的作用和用法有文件示例最好
C#中,索引器的作用和用法
有文件示例最好

C#中,索引器的作用和用法有文件示例最好
索引器的两种用法 和 作用 索引器允许您按照与数组相同的方式对类、结构或接口进行索引.有关对接口使用索引器的更多信息,请参见接口索引器. 要声明类或结构上的索引器,请使用 this 关键字,如下例所示: 复制代码 public int this[int index] // Indexer declaration { // get and set accessors } 备注 索引器类型及其参数类型必须至少如同索引器本身一样是可访问的.有关可访问级别的更多信息,请参见访问修饰符. 索引器的签名由其形参的数量和类型组成.它不包括索引器类型或形参名.如果在同一类中声明一个以上的索引器,则它们必须具有不同的签名. 索引器值不归类为变量;因此,不能将索引器值作为 ref 或 out 参数来传递. 要为索引器提供一个其他语言可以使用的名字,请使用声明中的 name 属性.例如: 复制代码 [System.Runtime.CompilerServices.CSharp.IndexerName("TheItem")] public int this [int index] // Indexer declaration { } 此索引器将具有名称 TheItem.不提供名称属性将生成 Item 默认名称. 示例1 说明 下面的示例说明如何声明私有数组字段、arr 和索引器.使用索引器可直接访问实例 test[i].另一种使用索引器的方法是将数组声明为 public 成员并直接访问它的成员 arr[i]. 代码 C# 复制代码 class IndexerClass { private int[] arr = new int[100]; public int this[int index] // Indexer declaration { get { // Check the index limits. if (index < 0 || index >= 100) { return 0; } else { return arr[index]; } } set { if (!(index < 0 || index >= 100)) { arr[index] = value; } } } } class MainClass { static void Main() { IndexerClass test = new IndexerClass(); // Call the indexer to initialize the elements #3 and #5. test[3] = 256; test[5] = 1024; for (int i = 0; i