namespace 索引器在接口中使用 { public interface Ifindex//定义一个接口 { int this[int index]//声明索引 { get; set; } } public class TestIndex:Ifindex//继承接口 { int[] myint = new int[10];//定义长度为10的int数组 public int this[int index]//索引访问器的定义 { get { if (index < 0 || index >= 10)//索引值不在这个范围就返回0 return 0; else return myint[index]; } set { if (index >= 0 && index < 10) myint[index] = value; //索引值在这个范围就正常赋值 } } } class Program { static void Main(string[] args) { TestIndex tix = new TestIndex();//实例化对象 tix[0] = 100;//用下标的形式给对象赋值 tix[1] = 300; tix[2] = 400; tix[3] = 500; Console.WriteLine(tix[0]);//打印输出 Console.WriteLine(tix[1]); Console.WriteLine(tix[2]); Console.WriteLine(tix[3]); Console.ReadKey(); } } }