日期:2014-05-17  浏览次数:20904 次

C# 请教一个存储数据结构的问题
1
  2
     3
     4
        5

有变量1,2,3,4,5,排列如上,把它们存储成什么结构,
可以通过下述方式获取这些值,请大虾们指点下,非常感谢!

b[0]=1
b[0][0]=2
b[0][0][0]=3
b[0][0][1]=4
b[0][0][0][0]=5

------解决方案--------------------
可以用indexer:

void Test()
{
    H b = new H(int.MinValue,
        new H(1,
            new H(2,
                new H(3),
                new H(4,
                    new H(5)
                )
            )
        )
    );
    int v = b[0][0][1][0];  // v== 5;
}

class H
{
    List<H> children = new List<H>();
    public H(int value, params H[] children)
    {
        this.Value = value;
        this.children.AddRange(children);
    }

    public H this[int index]   //<--
    {
        get { return children[index]; }
    }

    public int Value
    {
        get; set;
    }

    public int Add(H h)
    {
        children.Add(h);
        return children.Count - 1;
    }

    public static implicit operator int(H h)
    {
        return h.Value;
    }
}