现在的位置: 首页 > 综合 > 正文

面向对象程序设计: 索引器

2014年03月21日 ⁄ 综合 ⁄ 共 1979字 ⁄ 字号 评论关闭

------------------------
 索引器
------------------------
索引器允许类或结构的实例按照与数组相同的方式进行索引。索引器类似于属性,不同之处在于它们的访问器采用参数。要声明类或结构上的索引器,请使用 this 关键字,如下例所示:

public int this[int index]
{
    get {...}
    set {...}
}

示例 1

using System;
class IndexerClass
{
    private int[] arr = new int[100];
    public int this[int index]
    {
        get
        {
            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();
        test[3] = 256;
        test[5] = 1024;
        for (int i = 0; i <= 10; i++)
        {
         Console.WriteLine("Element #{0} = {1}", i, test[i]);
        }
    }
}

Element #0 = 0
Element #1 = 0
Element #2 = 0
Element #3 = 256
Element #4 = 0
Element #5 = 1024
Element #6 = 0
Element #7 = 0
Element #8 = 0
Element #9 = 0
Element #10 = 0
请按任意键继续. . .

示例解读:

在类中定义了一个数组字段,然后定义了一个索引器,如下

public int this[int index]{...}

其中
1 public为修饰符,还可以使用private等等。
2 int 指定索引类型。
3 this[int index]为索引声明,this表示当前对象,并且作为方括号的依附对象,方括号内容为索引值。
4 {...}为访问声明,写入一些可运行的语句,用于设置读取元素的值。

示例说明了如何声明私有数组字段arr 和索引器。使用索引器可直接访问实例 test[i]。另一种使用索引器的方法是将数组声明为 public 成员并直接访问它的成员 arr[i]。

示例 2

在此例中,声明了存储星期几的类。声明了一个 get 访问器,它接受字符串(天名称),并返回相应的整数。例如,星期日将返回 0,星期一将返回 1,等等。

class DayCollection
{
    string[] days = { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };
//这个方法用于输出准确的日期或-1
    private int GetDay(string testDay)
    {
        int i = 0;
        //枚举数组对象days中的元素保存到day中
        foreach (string day in days)
        {
            //比较day中某个元素是否和testDay相等
            if (day == testDay)
            {
                return i;
            }
            i++;
        }
        return -1;
    }

// 在索引器中附加get方法用于获取字符串
    public int this[string day]
    {
        get
        {
            return (GetDay(day));
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        DayCollection week = new DayCollection();
        System.Console.WriteLine(week["Fri"]);
        System.Console.WriteLine(week["Made-up Day"]);
    }
}

5
-1
请按任意键继续. . .

百思特网络 www.bestwl.com

抱歉!评论已关闭.