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#引入的一个新型的类成员,它使得对象可以像数组那样被方便,直观的引用。索引器非常类似于我们前面讲到的属性,但索引器可以有参数列表,且只能作用在实例对象上,而不能在类上直接作用。下面是个例子:
- // consume_cs_indexers.cs
- // compile with: /target:library
- using System;
- public class IndexerClass {
- private int [] myArray = new int[100];
- public int this [int index] { // Indexer declaration
- get {
- // Check the index limits.
- if (index < 0 || index >= 100)
- return 0;
- else
- return myArray[index];
- }
- set {
- if (!(index < 0 || index >= 100))
- myArray[index] = value;
- }
- }
- }
- /*
- // code to consume the indexer
- public class MainClass {
- public static void Main() {
- IndexerClass b = new IndexerClass();
- // Call indexer to initialize elements 3 and 5
- b[3] = 256;
- b[5] = 1024;
- for (int i = 0 ; i <= 10 ; i++)
- Console.WriteLine("Element #{0} = {1}", i, b[i]);
- }
- }
- */
转载于:https://blog.51cto.com/huqianhao/956561