用好索引器。
今天在CSDN上遇到一個(gè)問(wèn)題:
http://community.csdn.net/Expert/topic/4658/4658047.xml?temp=.6713526
樓主想用樹(shù)形的數(shù)據(jù),本來(lái)是可以用XmlDocument的,可這個(gè)東西的效率實(shí)在是太差,我們推薦他用Hashtable嵌套,后來(lái)說(shuō)寫(xiě)法太復(fù)雜。后來(lái)就想辦法用遞歸調(diào)用來(lái)簡(jiǎn)化語(yǔ)法。
搞了半天,忽然想起C++里面常常玩的鏈?zhǔn)奖磉_(dá)式的把戲,用下面的代碼實(shí)現(xiàn)了功能,而且用的時(shí)候?qū)懛胺Q完美。
?1public?class?TreeNode
?2??{
?3????Hashtable?_dictionary;
?4????string?_value?=?"";
?5
?6????public?TreeNode()
?7????{
?8??????_dictionary?=?new?Hashtable();
?9????}
10
11????public?TreeNode?this[string?key]
12????{
13??????get
14??????{
15????????if?(?key?==?null?)
16??????????throw?new?ArgumentNullException(?"key"?);
17
18????????EnsureChildNode(?key?);
19
20????????return?(TreeNode)?_dictionary[key];
21??????}
22??????set
23??????{
24????????if?(?key?==?null?)
25??????????throw?new?ArgumentNullException(?"key"?);
26
27????????EnsureChildNode(?key?);
28
29????????(?(TreeNode)?_dictionary[key]?).SetValue(?value._value?);
30??????}
31????}
32
33????private?void?EnsureChildNode(?string?key?)
34????{
35??????if?(?!_dictionary.ContainsKey(?key?)?)
36????????_dictionary.Add(?key,?new?TreeNode()?);
37????}
38
39????public?void?SetValue(?string?value?)
40????{
41??????if?(?value?==?null?)
42????????throw?new?ArgumentNullException(?"value"?);
43
44
45??????_value?=?value;
46????}
47
48????public?override?string?ToString()
49????{
50??????return?_value;
51????}
52
53????public?static?implicit?operator?TreeNode(?string?value?)
54????{
55??????TreeNode?node?=?new?TreeNode();
56??????node.SetValue(?value?);
57??????return?node;
58????}
59??}
60
轉(zhuǎn)載于:https://www.cnblogs.com/Ivony/archive/2006/04/03/365848.html
總結(jié)
- 上一篇: 小丫
- 下一篇: 使用泛型实现单例提供者(原创翻译)