索引器

一、索引器

C#中为了访问类的数组成员更加方便,更加直观,提供了索引器。

假设一个类如下:

class a
{
public int[] a = new int[20];
}

我们实例化他为_a,若想访问a的某个元素,其语法如下:

a _a = new a();
int m = _a.a[5];

如果类a定义了索引器,那么我们可以用如下的方法访问:

int m = _a[5];

这样显然代码更加简洁,逻辑上更直观。

下面代码展示了如何定义并使用一个索引器:

定义一个含有索引器的类:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace indexrTest
 7 {
 8     class xingxiIndexClass//作用是根据传入的字符串返回下标
 9     {
10         string[] days = { "a","b","c","d","e","f","g","h","i"};
11         private int getDay(string testDay)
12         {
13             for(int j=0;j<days.Length;j++)
14             {
15                 if(days[j] == testDay)
16                 {
17                     return j;
18                 }
19             }
20             throw new ArgumentOutOfRangeException(testDay, "testDay must be in the form "Sun", "Mon", etc");
21         }
22         public int this[string day]
23         {
24             get { return getDay(day); }
25         }
26     }
27 }
View Code

通过索引器访问类成员:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace indexrTest
{
    class Program
    {
        static void Main(string[] args)
        {
            fanxingClass<string> s = new fanxingClass<string>();
            s[0] = "这是一个索引器";
            Console.WriteLine(s[0]);
            xingxiIndexClass week = new xingxiIndexClass();
            Console.WriteLine(week["a"]);
            Console.WriteLine(week["测试范围之外的天"]);
        }
    }
}
Use Indexer

索引器的参数类型几乎可以是任意类型。定义规则是

[访问权限修饰符] [返回数据类型] this[参数类型 参数名]
{
get{}
set{}
}
原文地址:https://www.cnblogs.com/tntboom/p/3973127.html