C#中的索引器.docx

上传人:b****8 文档编号:10664170 上传时间:2023-02-22 格式:DOCX 页数:16 大小:18.94KB
下载 相关 举报
C#中的索引器.docx_第1页
第1页 / 共16页
C#中的索引器.docx_第2页
第2页 / 共16页
C#中的索引器.docx_第3页
第3页 / 共16页
C#中的索引器.docx_第4页
第4页 / 共16页
C#中的索引器.docx_第5页
第5页 / 共16页
点击查看更多>>
下载资源
资源描述

C#中的索引器.docx

《C#中的索引器.docx》由会员分享,可在线阅读,更多相关《C#中的索引器.docx(16页珍藏版)》请在冰豆网上搜索。

C#中的索引器.docx

C#中的索引器

索引器是C#的简单组件;为数组创建索引器后,可以通过从类对象指定索引来直接访问数组元素;可以用索引数组的方式索引对象;可以像访问数组一样访问类的成员

定义索引器的规则

必须指定至少一个索引器参数

应当为索引器参数赋值

【索引器】

索引器允许类或结构的实例就像数组一样进行索引。

索引器类似于属性,不同之处在于它们的访问器采用参数。

索引器在语法上方便您创建客户端应用程序可将其作为数组访问的类、结构或接口。

索引器经常是在主要用于封装内部集合或数组的类型中实现的。

使用索引器可以用类似于数组的方式为对象建立索引。

get访问器返回值。

set访问器分配值。

this关键字用于定义索引器。

value关键字用于定义由set索引器分配的值。

索引器不必根据整数值进行索引,由您决定如何定义特定的查找机制。

索引器可被重载。

索引器可以有多个形参,例如当访问二维数组时。

viewplaincopytoclipboardprint?

publicintthis[intindex]{//索引声明

//get和set访问器

}

publicintthis[intindex]{//索引声明

//get和set访问器

}

注意:

索引器类型及其参数类型必须至少如同索引器本身一样是可访问的。

索引器的签名由其形参的数量和类型组成。

它不包括索引器类型或形参名。

如果在同一类中声明一个以上的索引器,则它们必须具有不同的签名。

索引器值不属于变量;因此,不能将索引器值作为ref或out参数进行传递。

viewplaincopytoclipboardprint?

classTempRecord

{

//Arrayoftemperaturevalues

privatefloat[]temps=newfloat[10]{56.2F,56.7F,56.5F,56.9F,58.8F,

61.3F,65.9F,62.1F,59.2F,57.5F};

//Auto-ImplementedProperty

System.DateTimedate{get;set;}

//Toenableclientcodetovalidateinput

//whenaccessingyourindexer.

publicintLength

{

get{returntemps.Length;}

}

//Indexerdeclaration.

//Inputparameterisvalidatedbyclient

//codebeforebeingpassedtotheindexer.

publicfloatthis[intindex]

{

get

{

returntemps[index];

}

set

{

temps[index]=value;

}

}

}

classMainClass

{

staticvoidMain()

{

TempRecordtempRecord=newTempRecord();

//Usetheindexer'ssetaccessor

tempRecord[3]=58.3F;

tempRecord[5]=60.1F;

//Usetheindexer'sgetaccessor

for(inti=0;i<10;i++)

{

//Thisexamplevalidatestheinputontheclientside.Youmay

//choosetovalidateitintheclassthatimplementstheindexer,andthrowan

//exceptionorreturnanerrorcodeinthecaseofinvalidinput.

if(i

{

System.Console.WriteLine("Element#{0}={1}",i,tempRecord[i]);

}

else

{

System.Console.WriteLine("Indexvalueof{0}isoutofrange",i);

}

}

//Uncommentthiscodetoseehowthe.NETFrameworkhandlesindexerexceptions

//try

//{

//System.Console.WriteLine("Element#{0}={1}",tempRecord[tempRecord.Length]);

//}

//catch(System.ArgumentOutOfRangeExceptione)

//{

//System.Console.WriteLine(e);

//}

}

}

classTempRecord

{

//Arrayoftemperaturevalues

privatefloat[]temps=newfloat[10]{56.2F,56.7F,56.5F,56.9F,58.8F,

61.3F,65.9F,62.1F,59.2F,57.5F};

//Auto-ImplementedProperty

System.DateTimedate{get;set;}

//Toenableclientcodetovalidateinput

//whenaccessingyourindexer.

publicintLength

{

get{returntemps.Length;}

}

//Indexerdeclaration.

//Inputparameterisvalidatedbyclient

//codebeforebeingpassedtotheindexer.

publicfloatthis[intindex]

{

get

{

returntemps[index];

}

set

{

temps[index]=value;

}

}

}

classMainClass

{

staticvoidMain()

{

TempRecordtempRecord=newTempRecord();

//Usetheindexer'ssetaccessor

tempRecord[3]=58.3F;

tempRecord[5]=60.1F;

//Usetheindexer'sgetaccessor

for(inti=0;i<10;i++)

{

//Thisexamplevalidatestheinputontheclientside.Youmay

//choosetovalidateitintheclassthatimplementstheindexer,andthrowan

//exceptionorreturnanerrorcodeinthecaseofinvalidinput.

if(i

{

System.Console.WriteLine("Element#{0}={1}",i,tempRecord[i]);

}

else

{

System.Console.WriteLine("Indexvalueof{0}isoutofrange",i);

}

}

//Uncommentthiscodetoseehowthe.NETFrameworkhandlesindexerexceptions

//try

//{

//System.Console.WriteLine("Element#{0}={1}",tempRecord[tempRecord.Length]);

//}

//catch(System.ArgumentOutOfRangeExceptione)

//{

//System.Console.WriteLine(e);

//}

}

}

定义索引器的步骤:

指定确定索引器可访问性的访问修饰符。

索引器(由get访问器返回)的返回类型。

this关键字(this在这里作为索引器的名称,而且必须用this)。

左括号后面是索引器的数据类型和标识符,接着是右方括号。

左大括号表示索引器主体的开始,在此出定义get和set访问器,这与定义属性一样,最后插入右大括号。

【属性和索引器之间的比较】

索引器与属性类似。

除下表中显示的差别外,为属性访问器定义的所有规则同样适用于索引器访问器。

属性索引器

允许像调用公共数据成员一样调用方法。

允许对一个对象本身使用数组表示法来访问该对象内部集合中的元素。

可通过简单的名称进行访问。

可通过索引器进行访问。

可以为静态成员或实例成员。

必须为实例成员。

属性的get访问器没有参数。

索引器的get访问器具有与索引器相同的形参表。

属性的set访问器包含隐式value参数。

除了值参数外,索引器的set访问器还具有与索引器相同的形参表。

支持对自动实现的属性使用短语法。

不支持短语法。

【索引器与数组的比较】

索引器不指向内存位置

索引器可以有非整数的下标(索引)

可以重载索引器

【索引器与数组的比较】

viewplaincopytoclipboardprint?

usingSystem.Collections;

classStrIndex{

publicHashtablestudentList=newHashtable();

publicintthis[stringname]{

get{return(int)studentList[name];}

set{studentList[name]=value;}

}

}

classTest{

staticvoidMain(){

StrIndexobjIndex=newStrIndex();

objIndex["Sam"]=232676;

objIndex["Tom"]=455464;

System.Console.WriteLine("Sam的电话号码是{0},Tom的电话号码是{1}",

objIndex["Sam"],objIndex["Tom"]);

}

}

usingSystem.Collections;

classStrIndex{

publicHashtablestudentList=newHashtable();

publicintthis[stringname]{

get{return(int)studentList[name];}

set{studentList[name]=value;}

}

}

classTest{

staticvoidMain(){

StrIndexobjIndex=newStrIndex();

objIndex["Sam"]=232676;

objIndex["Tom"]=455464;

System.Console.WriteLine("Sam的电话号码是{0},Tom的电话号码是{1}",

objIndex["Sam"],objIndex["Tom"]);

}

}

索引器可以有非整数下标而数组不能有

【索引器与数组的比较】

viewplaincopytoclipboardprint?

usingSystem.Collections;

classIndexerExample{

publicstring[]stringList=newstring[10];

publicstringthis[intindex]{

get{returnstringList[index];}

set{stringList[index]=value.ToString();}

}

publicHashtablestudentList=newHashtable();

publicintthis[stringnumber]{

get{return(int)studentList[number];}

set{studentList[number]=value;}

}

}

classTest{

staticvoidMain(){

IndexerExampleindexTest=newIndexerExample();

indexTest.stringList[1]="Sam";

indexTest[2]="Tom";

indexTest["Sam"]=232;

indexTest["Tom"]=455;

}

}

usingSystem.Collections;

classIndexerExample{

publicstring[]stringList=newstring[10];

publicstringthis[intindex]{

get{returnstringList[index];}

set{stringList[index]=value.ToString();}

}

publicHashtablestudentList=newHashtable();

publicintthis[stringnumber]{

get{return(int)studentList[number];}

set{studentList[number]=value;}

}

}

classTest{

staticvoidMain(){

IndexerExampleindexTest=newIndexerExample();

indexTest.stringList[1]="Sam";

indexTest[2]="Tom";

indexTest["Sam"]=232;

indexTest["Tom"]=455;

}

}

【在索引器中使用多个参数】

索引器允许类或者结构的实例按照与数组相同的方式进行索引。

索引器类似属性,但不同之处在于它们的访问器采用参数。

它可以像数组那样对对象采用下标。

它提供了通过索引方式方便地访问类的数据信息的方法。

C#并不将索引类型限制为整数,所以我们可以通过访问器的重载,实现整数索引或者字符串索引。

重载索引器时,要保证形参的数量或形参类型至少有一不同。

这一点同C#中方法重载貌似没有什么区别。

下面我们就通过简单的例子,实现整数索引和字符串索引。

在这个例子中,我们需创建两个类-->Student  Students

Student类中,包含学生基本信息(属性)和一个方法SayHi()

Students类中,包含我们要创建的两种索引器,一个Student类类型的数组

Code:

1./// 

  

2.    /// Student类  具备学生基本属性  一个方法SayHi()  

3.    /// 

  

4.    public class Student  

5.    {  

6.        //构造函数  

7.        public Student(string name,int age,string hobby)   

8.        {  

9.            this.Name = name;  

10.            this.Age = age;  

11.            this.Hobby = hobby;  

12.        }  

13.  

14.        private string name;  

15.  

16.        public string Name  

17.        {  

18.            get { return name; }  

19.            set { name = value; }  

20.        }  

21.  

22.        private int age;  

23.  

24.        public int Age   

25.        {  

26.            get { return age; }  

27.            set { age = value; }  

28.        }  

29.  

30.        private string hobby;  

31.  

32.        public string Hobby   

33.        {  

34.            get { return hobby; }  

35.            set { hobby = value; }  

36.          

37.        }  

38.  

39.        // 方法  

40.        public void SayHi()   

41.        {  

42.            Console.WriteLine("大家好,我是{0},今年{1},我喜欢{2}",Name,Age.ToString(),Hobby);  

43.        }  

44.    }  

 

 

Code:

1./// 

  

2.   /// Students类,含有两种简答索引器  

3.   /// 

  

4.   public class Students  

5.   {  

6.  

7.       //构造函数  

8.       public Students()  

9.       {  

10.           stu[0] = new Student("rose",20,"dancing");  

11.           stu[1] = new Student("jack",21,"football");  

12.           stu[2] = new Student("mimi",20,"reading");  

13.       }  

14.       public Student[] stu = new Student[3];          //Student类型的数组  

15.  

16.  

17.       //简单整数索引器  

18.       public Student this[int index]   

19.       {  

20.           get   

21.           {  

22.               return stu[index];  

23.           }  

24.       }  

25.  

26.       //简单字符串索引器  

27.       public Student this[string name]   

28.       {  

29.           get   

30.           {  

31.               int i;  

32.               bool found = false;  

33.  

34.               for (i = 0; i < stu.Length; i++)   

35.               {  

36.                   if (stu[i].Name == name)   

37.                   {  

38.                       found = true;  

39.                       break;  

40.                   }  

41.               }  

42.               if (found)  

43.               {  

44.                   return stu[i];  

45.               }  

46.               else   

47.               {  

48.                   return null;  

49.               }  

50.           }  

51.       }  

52.   }  

Code:

1.class Program  

2.    {  

3.        static void Main(stri

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > PPT模板 > 国外设计风格

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1