索引器-经常用,但不常写,仅作为知识点了解一下
1:定义Person类,类中定义一个数组字段
2:为了方便外部访问,封装为属性
int[] numbers = new int[5];
public int[] Numbers {
get { return numbers; }
set { numbers = value; }
}
3:外部访问
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Indexer { class Program { static void Main(string[] args) { Person p = new Person(); p.Numbers = new int[] {1,2,2,3,8,5}; foreach (var item in p.Numbers) { Console.WriteLine(item); } Console.Read(); } } }
现在想不通过属性直接索引器访问.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Indexer { class Program { static void Main(string[] args) { Person p = new Person(); //p.Numbers = new int[] {1,2,2,3,8,5}; //foreach (var item in p.Numbers) //{ // Console.WriteLine(item); //} p[0] = 1; p[4] = 5; for (int i = 0; i < 5; i++) { Console.WriteLine(p[i]); } Console.Read(); } } }
4:进一步介绍索引器的重载,通过字典
Dictionary< string,int> dic = new Dictionary< string,int>();
public int this[string index]
{
set { dic[index] = value; }
get { return dic[index]; }
}
在main方法中调用
p["张三"] = 1;
Console.WriteLine(p["张三"]);