索引器!!的其他使用!

来源:互联网 发布:淘宝天猫首页优化 编辑:程序博客网 时间:2024/06/05 17:38

 备注

索引器类型及其参数类型必须至少如同索引器本身一样是可访问的。有关可访问级别的更多信息,请参见访问修饰符

索引器的签名由其形参的数量和类型组成。它不包括索引器类型或形参名。如果在同一类中声明一个以上的索引器,则它们必须具有不同的签名。

索引器值不归类为变量;因此,不能将索引器值作为 refout 参数来传递。

要为索引器提供一个其他语言可以使用的名字,请使用声明中的 name 属性。例如:

Copy Code
[System.Runtime.CompilerServices.IndexerName("TheItem")]public int this [int index]   // Indexer declaration{}

此索引器将具有名称 TheItem。不提供名称属性将生成 Item 默认名称。

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

C#
Copy Code
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]);        }    }}

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

请注意,当计算索引器的访问时(例如,在 Console.Write 语句中),将调用 get 访问器。因此,如果 get 访问器不存在,将发生编译时错误。

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

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

C#
Copy Code
// Using a string as an indexer valueclass 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"]);    }}

5

-1

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

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

  • 应当为 getset 访问器的可访问性设置尽可能多的限制。这一点对 set 访问器尤为重要。有关更多信息,请参见非对称访问器可访问性(C# 编程指南)

原创粉丝点击