C# 索引的作用和实现

官方描述:索引器允许类或结构的实例就像数组一样进行索引。索引器形态类似于,不同之处在于它们的取值函数采用参数。

这一功能在创建集合类的场合特别有用,而在其他某些情况下,比如处理大型文件或者抽象有些资源等,能让类具有类似数组行为也是非常有用的。

大致结构

<modifier><return type> this [argument list]

{

get{//读}

set{//写}

}

其中:

modifier:修饰符,如:public,private,protected

this:是C#中一个特殊的关键字,表示引用类的当前实例。这里是当前类的索引。

argument list:这里是索引器的参数

一个简单例子,通过索引器返回一个字符串:

class Sample { 
public string this [int index] { 
get {return "当前索引号为:" + index; } 
} 
} 

Sample s=new Sample();
Console.WriteLine(s[23]);

//结果
//当前索引号为:23

例子:从XML文件中获取配置信息,代码如下:

  xmlDoc.Load(configFileName);
            XmlNode urlNode = xmlDoc.SelectSingleNode("Config");
            HoradConfig url;
            foreach (XmlNode node in urlNode.ChildNodes)
            {
                if (node.Name != "AD")
                {
                    continue;
                }
                url = new HoradConfig();
                url.ID = node.Attributes["ID"].InnerText;
                url.Name = node.Attributes["Name"].InnerText;
                url.Remark = node.SelectSingleNode("Remark").InnerText.Trim();

                foreach (XmlNode ul in node.SelectNodes("Url"))
                {
                    if (ul.Attributes["apptype"] != null && ul.Attributes["apptype"].InnerText.Trim().Equals(appType.ToString()))
                    {
                        url.Type = ul.SelectSingleNode("Type")?.InnerText;
                        url.Data= ul.SelectSingleNode("Data")?.InnerText;
                        url.Bigad = ul.SelectSingleNode("Bigad")?.InnerText;
                    }
                }

                if (!string.IsNullOrEmpty(url.Bigad))
                {
                    urls.Add(url);
                }
            }

如上所示,在获取XML节点对应的信息时也用到了索引:

                url = new HoradConfig();
                url.ID = node.Attributes["ID"].InnerText;
                url.Name = node.Attributes["Name"].InnerText;
                url.Remark = node.SelectSingleNode("Remark").InnerText.Trim();

进入Attributes类看一看;

可以看到实现了三个索引,分别是int ,string 和string,string参数类型的;具体实现如下

 

 

技巧:

1.在定义索引器的时候,不一定只采用一个参数,同一类中还可以拥有一个以上的索引器,也就是重载。
2.索引器的参数可以采用任何类型,不过int是最为合理的类型。

属性和索引器差别

 1.类的每一个属性都必须拥有唯一的名称,而类里定义的每一个索引器都必须拥有唯一的签名(signature)或者参数列表(这样就可以实现索引器重载)。 

 2.属性可以是static(静态的)而索引器则必须是实例成员。 

 3.为索引器定义的访问函数可以访问传递给索引器的参数,而属性访问函数则没有参数。 

接口(interface):

类似数组的行为常受到程序实现者的喜爱,所以你还可以为接口定义索引器,IList和 IDictionary集合接口都声明了索引器以便访问其存储的项目。  在为接口声明索引器的时候,记住声明只是表示索引器的存在。你只需要提供恰当的访问函数即可,不必包括范围修饰符。以下代码把索引器声明为接口IImplementMe的一部分:

interface IImplementMe {  string this[int index]  {  get;  set;  } 

相应实现的类则必须为IimplementMe的索引器具体定义get和set访问函数。 

官方代码实例:

class SampleCollection<T>
{
    // Declare an array to store the data elements.
    private T[] arr = new T[100];

    // Define the indexer, which will allow client code
    // to use [] notation on the class instance itself.
    // (See line 2 of code in Main below.)        
    public T this[int i]
    {
        get
        {
            // This indexer is very simple, and just returns or sets
            // the corresponding element from the internal array.
            return arr[i];
        }
        set
        {
            arr[i] = value;
        }
    }
}

// This class shows how client code uses the indexer.
class Program
{
    static void Main(string[] args)
    {
        // Declare an instance of the SampleCollection type.
        SampleCollection<string> stringCollection = new SampleCollection<string>();

        // Use [] notation on the type.
        stringCollection[0] = "Hello, World";
        System.Console.WriteLine(stringCollection[0]);
    }
}
// Output:
// Hello, World.

码友实例:
非常实用

namespace Study
{
    class Program
    {
        static void Main(string[] args)
        {
            ScoreIndex s = new ScoreIndex();
            s["张三", 1] = 90;
            s["张三", 2] = 100;
            s["张三", 3] = 80;
            s["李四", 1] = 60;
            s["李四", 2] = 70;
            s["李四", 3] = 50;
            Console.WriteLine("张三课程编号为1的成绩为:" + s["张三",1]);
            Console.WriteLine("张三的所有成绩为:");
            ArrayList temp;
            temp = s["张三"];
            foreach (IndexClass b in temp) 
            {
                Console.WriteLine("姓名:" + b.Name + "课程编号:" + b.CourseID + "分数:" + b.Score);
            }
            Console.ReadKey();
        }
    }
    class IndexClass 
    {
        private string _name;
        private int _courseid;
        private int _score;
        public IndexClass(string _name, int _courseid, int _score) 
        {
            this._name = _name;
            this._courseid = _courseid;
            this._score = _score;
        }
        public string Name 
        {
            get { return _name; }
            set { this._name = value; }
        }
        public int CourseID 
        {
            get { return _courseid; }
            set { this._courseid = value; }
        }
        public int Score 
        {
            get { return _score; }
            set { this._score = value; }
        }
    }
    class ScoreIndex 
    {
        private ArrayList arr;
        public ScoreIndex() 
        {
            arr = new ArrayList();
        }
        public int this[string _name, int _courseid] 
        {
            get 
            {
                foreach (IndexClass a in arr) 
                {
                    if (a.Name == _name && a.CourseID == _courseid) 
                    {
                        return a.Score;
                    }
                }
                return -1;
            }
            set 
            {
                arr.Add(new IndexClass(_name, _courseid, value)); //arr["张三",1]=90
            }
        }
        //重载索引器
        public ArrayList this[string _name] 
        {
            get 
            {
                ArrayList temp = new ArrayList();
                foreach (IndexClass b in arr) 
                {
                    if (b.Name == _name) 
                    {
                        temp.Add(b);
                    }
                }
                return temp;
            }
        }
    }
}

 

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值