最近在做一個管理器類,老總要求裡面的Items屬性可以用索引器訪問,像Dictionary<T>一樣;但又要求唯讀不改。代碼剛剛成型,如有好的建議請提出。
1 /**//// <summary>
2 /// 泛型索引器
3 /// </summary>
4 /// <typeparam name="T">泛型</typeparam>
5 /// <seealso cref="System.Collections.Generic.IEnumerable<T>"/>
6 public class Indexer<T> : IEnumerable<T>
7 {
8 /**//// <summary>
9 /// 指向要用到
10 /// </summary>
11 private Dictionary<string, T> dict;
12
13 /**//// <summary>
14 /// 遇到錯誤時報錯
15 /// </summary>
16 private bool allowThrowReadError = false;
17
18 /**//// <summary>
19 /// 構造方法
20 /// </summary>
21 /// <param name="dict"></param>
22 /// <param name="allowThrowReadError">遇到錯誤時報錯</param>
23 public Indexer(Dictionary<string, T> dict,bool allowThrowReadError)
24 {
25 this.dict = new Dictionary<string, T>(dict);
26 }
27
28 /**//// <summary>
29 /// 索引器
30 /// </summary>
31 /// <param name="key">索引值</param>
32 /// <returns>傳回值</returns>
33 /// <typeparam name="T">泛型</typeparam>
34 /// <exception cref="Exception">當allowThrowReadError=true並且Key不存在時報異常</exception>
35 public T this[String key]
36 {
37 get
38 {
39 if (dict == null) throw new Exception("索引器失效");
40 if (dict.ContainsKey(key))
41 {
42 return dict[key];
43 }
44 if (allowThrowReadError) throw new Exception("不存在索引值");
45 else return default(T);
46 }
47 }
48
49 /**//// <summary>
50 /// 數目
51 /// </summary>
52 public int Count
53 {
54 get { return dict.Count; }
55 }
56
57 IEnumerator<T> IEnumerable<T>.GetEnumerator()
58 {
59 return dict.Values.GetEnumerator();
60 }
61
62 System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
63 {
64 return dict.Values.GetEnumerator();
65 }
66
使用設計管理員時的代碼:
管理器的屬性定義為