用好索引器。
今天在CSDN上遇到一個問題:
http://community.csdn.net/Expert/topic/4658/4658047.xml?temp=.6713526
樓主想用樹形的數據,本來是可以用XmlDocument的,可這個東西的效率實在是太差,我們推薦他用Hashtable嵌套,后來說寫法太復雜。后來就想辦法用遞歸調用來簡化語法。
搞了半天,忽然想起C++里面常常玩的鏈式表達式的把戲,用下面的代碼實現了功能,而且用的時候寫法堪稱完美。
?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
轉載于:https://www.cnblogs.com/Ivony/archive/2006/04/03/365848.html
總結
- 上一篇: 小丫
- 下一篇: 使用泛型实现单例提供者(原创翻译)