亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

類索引器的老生常談

標簽:
Ruby
 1 using System;
 2 using System.Collections.Generic;
 3 
 4 namespace Prototype
 5 {
 6     class Program
 7     {
 8         static void Main(string[] args)
 9         {
10             PersonContainer pc = new PersonContainer();
11             pc[1] = new Person() { No = 1, Age = 30, Name = "杨俊明" };
12             pc[2] = new Person() { No = 2, Age = 30, Name = "Mike" };
13 
14             Console.WriteLine(pc[1] + "\n" + pc[2] + "\n" + pc[3]);
15 
16             Console.WriteLine(pc["杨俊明"] + "\n" + pc["MIKE"] + "\n" + pc["NotExists"]);
17 
18             Console.Read();
19 
20         }        
21     }  
22 
23 
24     public class Person
25     {
26         public int No { set; get; }
27         public string Name { set; get; }
28         public int Age { set; get; }
29 
30         public override string ToString()
31         {
32             return string.Format("No:{0},Name:{1},Age:{2}", No, Name, Age);
33         }
34     }
35 
36     public class PersonContainer
37     {
38         Dictionary<int, Person> dics = new Dictionary<int, Person>();
39 
40         /// <summary>
41         /// 类索引器
42         /// </summary>
43         /// <param name="no"></param>
44         /// <returns></returns>
45         public Person this[int no]
46         {
47             get
48             {
49                 if (dics.ContainsKey(no))
50                 {
51                     return dics[no];
52                 }
53                 else
54                 {
55                     return null;
56                 }
57             }
58             set
59             {
60                 if (!dics.ContainsKey(no))
61                 {
62                     dics.Add(no, value);
63                 }
64                 else
65                 {
66                     dics[no] = value;
67                 }
68             }
69         }
70 
71         /// <summary>
72         /// 类索引器重载
73         /// </summary>
74         /// <param name="name"></param>
75         /// <returns></returns>
76         public Person this[string name]
77         {
78             //只读
79             get
80             {
81                 Person _person = null;
82                 foreach (Person _p in dics.Values)
83                 {
84                     if (string.Compare(_p.Name, name, true) == 0)
85                     {
86                         _person = _p;
87                         break;
88                     }
89                 }
90 
91                 return _person;
92             }
93         }
94     }
95 }
96


點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消