C# 索引器的实现过程

来源:互联网 发布:上海网络香烟销售 编辑:程序博客网 时间:2024/06/10 09:12

       类的每一个属性都必须拥有一个唯一的名称,而类里定义的每一个索引器都必须拥有唯一的签名

或者参数列表,这样就可以实现索引器重载。属性可以是static,而索引器必须是实例成员。为索

引器定义的访问函数可以访问传递给索引器的参数,而属性访问函数则没有参数我们也可以为接

口定义索引器,在为接口声明索引器的时候,记住声明只是表示索引器的存在,你只需要提供恰

当的访问函数即可不必包括修饰符。

看下面案例:

ITestIndex.cs文件

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace AlgorithmDemo{    interface ITestIndex    {        string this[int index]        {            get;            set;        }    }}
TestIndex.cs文件

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace AlgorithmDemo{    class TestIndex<T>    {        private T[] arr = new T[100];        public T this[int i]        {            get { return arr[i]; }            set { arr[i] = value;}        }    }}
Program.cs

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace AlgorithmDemo{    class Program    {        static void Main(string[] args)        {            TestIndex<string> test = new TestIndex<string>();            string data = "hello,world!";            for (int i = 0; i < data.Length; i++)            {                test[i] = data[i].ToString();            }            for (int i = 0; i < data.Length; i++)            {                Console.Write(test[i]);            }            while (true) ;        }    } }            
效果图:






















0 0
原创粉丝点击