C#索引器

来源:互联网 发布:2016年最火的网络用语 编辑:程序博客网 时间:2024/04/29 01:15

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

 

修饰符包括 public,protected,private,internal,new,virtual,sealed,override, abstract,extern.

 

在下面的示例中,定义了一个泛型类,并为其提供了简单的 getset 访问器方法(作为分配和检索值的方法)。Program 类为存储字符串创建了此类的一个实例。

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]);
    }
}
索引器概述

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

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

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

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

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

  • 索引器可被重载。

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

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

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

  • 接口访问器没有体。

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

以下是接口索引器访问器的示例:

public interface ISomeInterface
{
    //...

    // Indexer declaration:
    string this[int index]
    {
        get;
        set;
    }
}
一个索引器的签名必须区别于在同一接口中声明的其他所有索引器的签名。

// Indexer on an interface:
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]);
        }
    }
}

在上例中,可以通过使用接口成员的完全限定名来使用显式接口成员实现。例如:

public string ISomeInterface.this { } 

但是,只有当类使用同一索引器签名实现一个以上的接口时,为避免多义性才需要使用完全限定名。例如,如果 Employee 类实现的是两个接口 ICitizenIEmployee,并且这两个接口具有相同的索引器签名,则必须使用显式接口成员实现。即,以下索引器声明:

public string IEmployee.this { } 

IEmployee 接口上实现索引器,而以下声明:

public string ICitizen.this { } 

ICitizen 接口上实现索引器。

 

来自:http://msdn.microsoft.com/zh-cn/library/6x16t2tx(v=VS.80).aspx

原创粉丝点击