打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C#中的索引的入门 - 李浩的博客园 - 博客园

C#中的索引器是新增加的,和属性有些不同。在C#中,属性可以是这样的:

class Person {
private string firstname;
public string FirstName
 {
get {return firstname;}

set {firstname = value;}
}

}

属性声明可以如下编码: 
Person p = new Person();
p.FirstName = "TOM";
Console.WriteLine (p.FirstName);

  属性声明倒更像是域声明,只不过它还声明了两个特殊的成员,按照微软的说法就是所谓的访问函数(accessor)(见代码中浅黄色部分)。当某一表达式的右边调用属性或者属性用作其他子程序(或者函数)的参数时即会调用get访问函数。反之,当表达式左边调用属性并且通过隐式传递value参数设置私有域值的情况下就会调用set访问函数。
  索引器(Indexer)是C#引入的一个新型的类成员,它使得对象可以像数组那样被方便,直观的引用。索引器非常类似于我们前面讲到的属性,但索引器可以有参数列表,且只能作用在实例对象上,而不能在类上直接作用。下面是个例子:

 

01 using System;
02 using System.Collections.Generic;
03 using System.Linq;
04 using System.Text;
05   
06 namespace ConsoleApplication1
07 {
08     public class MyPreviousExp
09     {
10           
11         private string[] myCompanies = new string[10];
12   
13          //index creation
14         public string this[int index]{
15                       <SPAN style="BACKGROUND-COLOR: #ffff00">get</SPAN>
16                       {
17                        if(index <0 || index >= 6)
18                         return "null"
19                        else
20                         return myCompanies[index];
21                       
22                       <SPAN style="BACKGROUND-COLOR: #ffff00">set</SPAN>
23                       {
24                        if(!(index <0 || index >= 10))
25                         myCompanies[index] = value;
26                       }
27   
28         }
29           
30         public static void Main()
31         {
32             MyPreviousExp indexerObj = new MyPreviousExp();
33   
34             indexerObj[0] = "AMS";
35             indexerObj[3] = "HCL";
36             indexerObj[5] = "ACC";
37             indexerObj[8] = "OFW";
38             for (int i = 0; i < 10; i++)
39             {
40                 Console.WriteLine(" My Companies{0} : {1} ", i, indexerObj[i]);
41             }
42         }
43     }
44 }

 

输出结果为:

01 My Companies0 : AMS
02 My Companies1 :
03 My Companies2 :
04 My Companies3 : HCL
05 My Companies4 :
06 My Companies5 : ACC
07 My Companies6 : null
08 My Companies7 : null
09 My Companies8 : null
10 My Companies9 : null
可以看到,索引不仅仅是对一个数组成员的访问,因为 

 

indexerObj[8] = "OFW"; 

处是有值的,但是在输出中却显示了

My Companies8 : null ,

出现这样的原因是在 get accessor中有这样一行代码

1 if(index <0 || index >= 6)
1 return "null";

所以即使是在[]的参数列表中有访问到位置8,也不能成功输出,更甚,可以在 get accessor 中乱写,达到一些根本就不是索引器该做的工作,例如全部输出 1 之类,但是这不是 accessor 的本意,就不在这里赘述了。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Spring Data JDBC参考文档二
javaScript
C# 9.0新特性详解系列之一:只初始化设置器(init only setter)
30分钟掌握 C#6
JSON Binding API 入门,第 2 部分: 通过 JSON
spring-data-jpa 中文文档(2)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服