C#的索引器如何实现,索引器是用作什么的。新手求高手指点。谢谢。

解决方案 »

  1.   


    //MSDN提供的代码
    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]);
        }
    }
      

  2.   

    下面的代码就是定义一个索引器public SubjectContent this[string strID]
            {
                get
                {
                    for (int i = 0; i < this.InnerList.Count; i++)
                    {
                        if ((this.InnerList[i] as SubjectContent).ID.ToString() == strID)
                        {
                            return (this.InnerList[i] as SubjectContent);
                        }
                    }
                    return null;
                }
            }
    索引器允许按照数组的额方式索引对象的数组元素,索引器可以使用户像访问数组一样访问类成员,索引器类似于属性,不同之处在于它们的访问器采用参数。
      

  3.   

    索引器就是一类特殊的属性,可以像引用数组一样引用自己的类
    索引器属于实例成员,不能被声明为static 
    http://zzk.cnblogs.com/s?w=%E7%B4%A2%E5%BC%95%E5%99%A8
      

  4.   

    比如说你在web里面的querystring可以这样访问querystring【0】也可以这样访问querystring【“ID”】
    就是实现这样的功能的