索引器方法

来源:互联网 发布:花与剑 js 编辑:程序博客网 时间:2024/06/02 21:28

1.C#允许构建按照标准数组方式索引的自定义类和结构,以这种方式访问子项的方法成为索引器方法。

public class MyClass1
    {
        private ArrayList arrTest = new ArrayList();
        public Object this[int index]
        {
            get { return arrTest[index]; }
            set { arrTest.Insert(index, value); }
        }

    }

索引器的声明和属性非常相似,在自定义集合类型中支持索引器方法后,能很好的和.net基础类库融为一体。泛型类型直接支持这个功能

2.

public class MyClass1
    {
        private List<int> listInt = new List<int> { 1, 2, 3, 4, 5 };
        private void Func1()
        {
            listInt[0] = 0; //直接使用索引器改变第一个数据
            for (int i = 0; i < listInt.Count; i++)
            {
                Console.WriteLine(listInt[i].ToString());
            }

        }
    }

3.示例:

public class MyClass2
    {
        public int X { get; set; }
        public int Y { get; set; }
    }
    public class MyClass3
    {
        private Dictionary<string, MyClass2> dictionaryTest = new Dictionary<string, MyClass2>();
        public MyClass2 this[string s]
        {
            get { return dictionaryTest[s]; }
            set { dictionaryTest[s] = value; }
        }

    }

4.索引器方法的重载

ADO.NET中DataSet类支持一个Tables的属性,返回强类型的DataTableCollection类型。

//重载索引器方法

public DataTable this[string name] {get;}

public DataTable this[int index]{get;}

...

5.在接口类型上定义索引器

public interface Itest
    {
        string this[int index] { get; set; }  //任何实现了该接口的类和结构都必须支持一个可读写的索引器
    }

0 0
原创粉丝点击