索引器是C#是一个比较特殊的功能,
它一般用来提供数组/集合被外部访问的接口(其实就是对集合或数组成员的方便的操作 eg:获取OR设置数组/集合元素…)
C#的索引器定义在类中,可以重载(索引可以不是整形,也就是可以快速访问Dictionary[即map]),
需要注意的点
它固定要有get,set的方法,get需要返回要取的值
set方法由于没有参数,看似不可以赋值,但其提供了一个默认的value关键字
public class Kingdom { private List<string> dux; public Kingdom() { } public Kingdom(List<string> dux) { this.dux = dux; } public string this[int num] { get { if (dux == null) return "未初始化"; if (num < 0 || num > dux.Count) return "內容為空"; return dux[num]; } set { if (dux == null) Console.WriteLine("未初始化"); if(num<0||num>dux.Count) Console.WriteLine("錯誤的放入位置"); dux[num] = value; } } }
测试:
public static void Main(string[] args) { List<string> dux = new List<string>() { "奥尔良","勃艮第","阿尔玛尼克","阿基坦","布列塔尼","诺曼底"}; Kingdom france = new Kingdom(dux); france[1] = "图卢兹"; for(int i = 0; i < dux.Count; i++) { Console.WriteLine(france[i]); } }
结果:
奥尔良 图卢兹 阿尔玛尼克 阿基坦 布列塔尼 诺曼底
对Dictionary也是如此
public class Kingdom { private Dictionary<string,string> dux; public Kingdom() { } public Kingdom(Dictionary<string, string> dux) { this.dux = dux; } //索引的值可以不为整形 public string this[string num] { get { if (dux == null) return "未初始化"; if (dux[num]==null) return "內容為空"; return dux[num]; } set { if (dux == null) Console.WriteLine("未初始化"); if (dux[num]==null) Console.WriteLine("錯誤的放入位置"); dux[num] = value; } } }
public static void Main(string[] args) { Dictionary<string, string> duxes = new Dictionary<string, string>(); duxes.Add("a", "b"); duxes.Add("c","d"); duxes.Add("e", "f"); Kingdom france = new Kingdom(duxes); france["c"] = "abcdefg"; var keys = duxes.Keys; foreach(string str in keys) { Console.WriteLine(france[str]); } }
b abcdefg f