Contents

索引器

Contents

索引器

  • 让对象可以像数组一样通过索引访问其中元素,使程序看起来更直观,更容易编写
  • 索引器的参数类型可以是任意类型

基本语法

class Person{
    private string name;
    private int age;
    private Person[] friends;
    private int[,] array;
    public Person this[int index] {
        get{
            return friend[index];
        }
        set{
            friends[index] = value;
        }
    }
    //索引器重载
    public int this[int i,int j]{
        get{
            return array[i,j];
        }
        set{
            array[i,j] = value;
        } 
    }
}
Person p = new Person();
p[0] = new Person();//访问set方法
Console.WriteLine(p[0].name);//访问get方法
p[0,0] = 10;