索引器

来源:互联网 发布:最安全的算法 编辑:程序博客网 时间:2024/04/30 15:54
CLR(公共语言运行时)提供了两种属性:无参属性和含参属性,在C#中,前者通常被称为属性(property),
后者被称为索引器(indexer)。

定义索引器的方式如下:

[修饰符] 数据类型 this[索引类型 index]

{

get{//返回属性的代码};

set{//获得属性的代码};

}

属性:

[修饰符] 数据类型 属性名

{

get{};

set{};

}

修饰符:包括public,protected,private,internal,new,virtual,sealed,override, abstract,extern.

数据类型:是表示将要存取的数组或集合元素的类型。

索引器类型: 表示该索引器使用哪一类型的索引来存取数组或集合元素,可以是整数,可以是字符串;this表示操作本对象的数组或集合成员,可以简单把它理解成索引器的名字,因此索引器不能具有用户定义的名称

索引器的用来做什么:

自定义泛型,用到索引器

namespace 索引器
{
    class Program
    {
        static void Main(string[] args)
        {
            SampleCollection<string> stringCollection = new SampleCollection<string>();
            stringCollection[0] = "Hello, World";
            stringCollection[1] = "goodbye,yesterday";
            Console.WriteLine(stringCollection[0]);
            Console.WriteLine(stringCollection[1]);
            Console.ReadKey();
        }
    }
    //定义泛型<T> ArrayList/(List<T>,Dictionay<T1,T2>)键值对的方式添加数据/HashTable
    class SampleCollection<T>
    {
        private T[] arr = new T[100];  //存储数组长度为100组,索引器类似属性,只是索引器用于数组的赋值,取值
        public T this[int i]
        {
            get
            {
                return arr[i];
            }
            set
            {
                arr[i] = value;
            }
        }
    }




0 0