[]
 The array indexing operator cannot be overloaded, but you can define indexers.
 
这个是CSDN上的说明,是说不能重载
但很多类(比如System.Collections namespace下的很多类)都有[]运算符,这个应该怎么理解我自己的类该如何重载这个操作符?

解决方案 »

  1.   

    给你的类添加一个索引就可以了,按如下的代码:
    class class a
    {
        public int this[int index]
        {
            get
            {
                 return ...
            }
            set
            {  
                 ...=value;
            }
        }
    }
      

  2.   

    以前也没注意过这个问题..不知道是否可以这样理解呢?public class Test
        {
            private ArrayList list;
            public Test()
            {
                list = new ArrayList();
            }
            public string this[int index]
            {
                get { return list[index].ToString (); }
                set { list[index] = value; }
            }        public void Add(string str)
            {
                list.Add(str);
            }
            public int Count()
            {
                return list.Count;
            }
        }测试:
     Test test = new Test();
                test.Add("aaa");
                test.Add("bbb");
                test.Add("ccc");
                test[1] = "ddd";
                for (int i = 0; i < test.Count(); i++)
                {
                    Console.WriteLine(test[i]);
                }
      

  3.   

    还请hbxtlhx(平民百姓)大哥指正..
      

  4.   

    这更重再有什么关系
    也可以
    public object this[int]
    public object this[int,string.....] //任意参数
      

  5.   

    TO:这更重再有什么关系
    也可以
    public object this[int]
    public object this[int,string.....] //任意参数TO:是的,一个类可以有多个不同类型的索引重载,可是觉得楼主描述的问题好像是没有实现索引的问题...是的,一通百通,这些也都是理所当然的了..呵呵..谢谢..