c#_索引器(Indexer)

来源:互联网 发布:windows phone7.8评测 编辑:程序博客网 时间:2024/05/15 02:21
//索引器(Indexer) 允许一个对象可以像数组一样被索引。当您为类定义一个索引器时,该类的行为就会像一个 虚拟数组(virtual array) 一样。您可以使用数组访问运算符([ ])来访问该类的实例。//语法  如下: //element-type this[int index] //{//   // get 访问器//   get //   {//      // 返回 index 指定的值//   } //   // set 访问器//   set //   {//      // 设置 index 指定的值 //   }//}public class Indexer //: IEnumerable{static public int size = 10;private string[] indexerList = new string[size];//构造函数赋初值public Indexer(){for (int i = 0; i < indexerList.Length; i++)indexerList[i] = "DefaultValue";}//c# 索引器public string this[int index]{get{if (index < 0 || index > size)return "";return indexerList[index] == null ? string.Empty : indexerList[index].ToString();}set{if (index < 0 || index > size)throw new Exception("超出索引范围: 0~9");indexerList[index] = value;}}//实现foreach枚举public IEnumerator GetEnumerator(){return this.indexerList.GetEnumerator();}   }//索引器调用测试Indexer id = new Indexer();id[0] = "0";id[1] = "1";id[6] = "6";foreach (string strTmp in id)Console.WriteLine(strTmp);Console.ReadKey();//0//1//////////6//////


0 0
原创粉丝点击