用好索引器。
2006-04-03 17:58 Ivony... 阅读(628) 评论(0) 编辑 收藏 举报今天在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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!