用好索引器。

今天在CSDN上遇到一个问题:

http://community.csdn.net/Expert/topic/4658/4658047.xml?temp=.6713526

楼主想用树形的数据,本来是可以用XmlDocument的,可这个东西的效率实在是太差,我们推荐他用Hashtable嵌套,后来说写法太复杂。后来就想办法用递归调用来简化语法。

搞了半天,忽然想起C++里面常常玩的链式表达式的把戏,用下面的代码实现了功能,而且用的时候写法堪称完美。

 1None.gifpublic class TreeNode
 2ExpandedBlockStart.gifContractedBlock.gif  dot.gif
{
 3
InBlock.gif    Hashtable _dictionary;
 4InBlock.gif    string _value = ""
;
 5
InBlock.gif
 6InBlock.gif    public
 TreeNode()
 7ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif
{
 8InBlock.gif      _dictionary = new
 Hashtable();
 9ExpandedSubBlockEnd.gif    }

10InBlock.gif
11InBlock.gif    public TreeNode this[string
 key]
12ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif
{
13InBlock.gif      get

14ExpandedSubBlockStart.gifContractedSubBlock.gif      dot.gif{
15InBlock.gif        if ( key == null
 )
16InBlock.gif          throw new ArgumentNullException( "key"
 );
17
InBlock.gif
18
InBlock.gif        EnsureChildNode( key );
19
InBlock.gif
20InBlock.gif        return
 (TreeNode) _dictionary[key];
21ExpandedSubBlockEnd.gif      }

22InBlock.gif      set
23ExpandedSubBlockStart.gifContractedSubBlock.gif      dot.gif{
24InBlock.gif        if ( key == null
 )
25InBlock.gif          throw new ArgumentNullException( "key"
 );
26
InBlock.gif
27
InBlock.gif        EnsureChildNode( key );
28
InBlock.gif
29
InBlock.gif        ( (TreeNode) _dictionary[key] ).SetValue( value._value );
30ExpandedSubBlockEnd.gif      }

31ExpandedSubBlockEnd.gif    }

32InBlock.gif
33InBlock.gif    private void EnsureChildNode( string
 key )
34ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif
{
35InBlock.gif      if ( !
_dictionary.ContainsKey( key ) )
36InBlock.gif        _dictionary.Add( key, new
 TreeNode() );
37ExpandedSubBlockEnd.gif    }

38InBlock.gif
39InBlock.gif    public void SetValue( string
 value )
40ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif
{
41InBlock.gif      if ( value == null
 )
42InBlock.gif        throw new ArgumentNullException( "value"
 );
43
InBlock.gif
44
InBlock.gif
45InBlock.gif      _value =
 value;
46ExpandedSubBlockEnd.gif    }

47InBlock.gif
48InBlock.gif    public override string
 ToString()
49ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif
{
50InBlock.gif      return
 _value;
51ExpandedSubBlockEnd.gif    }

52InBlock.gif
53InBlock.gif    public static implicit operator TreeNode( string
 value )
54ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif
{
55InBlock.gif      TreeNode node = new
 TreeNode();
56
InBlock.gif      node.SetValue( value );
57InBlock.gif      return
 node;
58ExpandedSubBlockEnd.gif    }

59ExpandedBlockEnd.gif  }

60None.gif

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值