泛型索引器類代碼

來源:互聯網
上載者:User
最近在做一個管理器類,老總要求裡面的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

使用設計管理員時的代碼:
管理器的屬性定義為

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.