C#索引器

来源:互联网 发布:linux 监控工具 编辑:程序博客网 时间:2024/06/11 03:11

所谓索引器就是一类特殊的属性,通过它们你就可以像引用数组一样引用自己的对象。 特别是属性,每一个元素都以一个get或set方法暴露。而索引器最大的好处是使代码看上去更自然,更符合实际的思考模式

索引器非常类似于属性,但索引器可以有参数列表,且只能作用在实例对象上,不能在类上直接作用

private int[]  arrMyInt=new int[100];
public int this[int index]    //索引器申明
{
     get{
  return arrMyInt[index];
 }
 set{
  arrMyInt[index]=value;
 }
}

public class Items
  {
   private string[] strItems = new string[256];

   public string this[int index]
   {
    get
    {
     if (index<0 || index>=strItems.Length)
      Console.WriteLine(("非法索引")); 
     return strItems[index];
    }
    set
    {
     strItems[index] = value;
    }
   }
  }

在上面的代码中我们申明了一个类,这个类有一个索引器,它的索引名后面跟着一个索引值index的定义。那么现在我们来看看怎么样使用那个类和索引器呢。
   Items items = new Items();

   items[0] = "333";
   items[1] = "234";

    Console.WriteLine(items[0] + items[1]);
 我们只需定义这个对象,同时在对象后面加上索引就可以很轻易的使用对应索引的值了,你们看看是不是很容易理解呢?

 

原创粉丝点击