| using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Team { private int[] arr = new int[100]; public int this[int index] // Indexer declaration { get { // Check the index limits. //if (index < 0 || index >= 100) if ((index == 3)||(index==5)) { return arr[index]; } else { //其它除了3与5索引的元素,在调用方查询时全是777 return 777; } } set { //索引访问器的供值优先级高于 调用此类对象的供值语句 Team test = new Team(); test[3] = 256; if (index == 3 || index == 5) { arr[index] = 233444; } } } } } |
调用上述包含索引访问器的TEAM类
| using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Team test = new Team(); // 3与5号索引有数据,其它全是元素全是0 注:此直接供值被team类的索引访问器set屏掉 //即set优先极高于下述2行代码 test[3] = 256; test[5] = 1024; for (int i = 0; i <= 10; i++) { //使用的是get索引访问器 System.Console.WriteLine("Element #{0} = {1}", i, test[i]); } Console.ReadKey(); } } } |
调试结果
| Element #0 = 777 //对应get的else分支 Element #1 = 777 Element #2 = 777 Element #3 = 233444 //对应set部分 Element #4 = 777 Element #5 = 233444 Element #6 = 777 Element #7 = 777 Element #8 = 777 Element #9 = 777 Element #10 = 777 |