写一个未指定的Rank和Size数组

时间:2012-04-02 15:12:42

标签: c# .net arrays

如何编写未指定等级和大小的数组的每个元素?

为了更加明确,我还为MSTest编写了一些测试用例。 这三个测试检查标量,一维和二维数据以及字符串,双精度和整数数据。

[TestMethod()]
public void TestWrittenScalarIsCorrect()
{
    Array data = Array.CreateInstance(typeof(string), 1);
    data.SetValue("hello", 0);
    Assert.AreEqual(0, data.Rank);
    // nothing fancy
    Assert.AreEqual("[hello]", WriteArray(data));
}

[TestMethod()]
public void TestWritten1DIsCorrect()
{
    // note: I'm expecting 1.0 => '1'
    Assert.AreEqual("[1, 1.1]", 
        YamlWriter.WriteArray(new double[] { 1.0, 1.1 }));
}

[TestMethod()]
public void TestWritten2DIsCorrect()
{
    // Note: expecting 00 and 01 to be 0 and 1, respectively
    Assert.AreEqual("[[0, 1], [10, 11]]", 
        WriteArray(new int[,]{ {0, 1}, {10, 11}}));
}

[TestMethod()]
public void TestWritten3DIsCorrect()
{
    var data = new int[3, 3, 3];
    for (int kk = 0; kk < 3; kk++)
    {
        for (int jj = 0; jj < 3; jj++)
        {
            for (int ii = 0; ii < 3; ii++)
            {
                data[kk, jj, ii] = kk * 100 + jj * 10 + ii;
            }
        }
    }

    // Note: expecting 00 and 01 to be 0 and 1, respectively
    Assert.AreEqual("[[[0, 1, 2], [10, 11, 12], [20, 21, 22]], "
                   + "[[100, 101, 102], [110, 111, 112], [120, 121, 122]], "
                   + "[[200, 201, 202], [210, 211, 212], [220, 221, 222]]]",    
           WriteArray(data));
}

谢谢!

1 个答案:

答案 0 :(得分:1)

如果我理解正确,你需要这样的东西:

    public string WriteArray(Array data)
    {
        return WriteArray(data, new Stack<int>());
    }

    public string WriteArray(Array data, Stack<int> dim)
    {
        //edit
        if (dim.Count == data.Rank) return data.GetValue(dim.Reverse().ToArray()).ToString();

        List<string> elementStrings = new List<string>();
        int length = data.GetLength(dim.Count);

        for (int i = 0; i < length; i++)
        {
            dim.Push(i);
            string elem = WriteArray(data, dim);
            dim.Pop();

            elementStrings.Add(elem);
        }

        return "[" + string.Join(", ", elementStrings) + "]";
    }

编辑:添加了缺失的.Reverse()