您的位置:首页 > 编程语言 > C#

浅析C#中的索引器

2015-09-07 08:46 357 查看
索引器允许类或结构的实例按照与数组相同的方式进行索引。索引器类似于属性,不同之处在于它们的访问器采用参数。

索引器概述

索引器使得对象可按照与数组相似的方法进行索引。

get 访问器返回值。set 访问器分配值。

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

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

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

索引器可被重载。

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

class SampleCollection<T>
{
    private T[] arr = new T[100];
    public T this[int i]
    {
        get
        {
            return arr[i];
        }
        set
        {
            arr[i] = value;
        }
    }
}

// This class shows how client code uses the indexer
class Program
{
    static void Main(string[] args)
    {
        SampleCollection<string> stringCollection = new SampleCollection<string>();
        stringCollection[0] = "Hello, World";
        System.Console.WriteLine(stringCollection[0]);
    }
}


使用索引器

索引器允许您按照处理数组的方式索引类、结构或接口。

要声明类或结构上的索引器,请使用 this 关键字,如下例所示:

public int this[int index] // Indexer declaration

{

// get and set accessors

}

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 <= 10; i++)
        {
            System.Console.WriteLine("Element #{0} = {1}", i, test[i]);
        }
    }
}


出乎你的意料,使用其他值进行索引

C# 并不将索引类型限制为整数。例如,对索引器使用字符串可能是有用的。通过搜索集合内的字符串并返回相应的值,可以实现此类的索引器。由于访问器可被重载,字符串和整数版本可以共存。

// Using a string as an indexer value
class DayCollection
{
    string[] days = { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };

    // This method finds the day or returns -1
    private int GetDay(string testDay)
    {
        int i = 0;
        foreach (string day in days)
        {
            if (day == testDay)
            {
                return i;
            }
            i++;
        }
        return -1;
    }

    // The get accessor returns an integer for a given string
    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"]);
    }
}


提高索引器的安全性和可靠性有两种主要的方法:

当设置并检索来自索引器访问的任何缓冲区或数组的值时,请始终确保您的代码执行范围和类型检查。

应当为 get 和 set 访问器的可访问性设置尽可能多的限制。这一点对 set 访问器尤为重要。

接口中的索引器

索引器可在接口(C# 参考)上声明。接口索引器的访问器与类索引器的访问器具有以下方面的不同:

*接口访问器不使用修饰符。*

*接口访问器没有体。*

因此,访问器的用途是指示索引器是读写、只读还是只写。

public interface ISomeInterface
{
    // Indexer declaration:
    int this[int index]
    {
        get;
        set;
    }
}

// Implementing the interface.
class IndexerClass : ISomeInterface
{
    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 #2 and #5.
        test[2] = 4;
        test[5] = 32;
        for (int i = 0; i <= 10; i++)
        {
            System.Console.WriteLine("Element #{0} = {1}", i, test[i]);
        }
    }
}


属性与索引器之间的比较

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

属性:

允许调用方法,如同它们是公共数据成员。

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

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

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

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

索引器:

允许调用对象上的方法,如同对象是一个数组。

可通过索引器进行访问。

必须为实例成员。

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

除了 value 参数外,索引器的 set 访问器还具有与索引器相同的形参表。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: