如何将多维数组转换为任意类型?

时间:2013-09-12 22:37:53

标签: c# arrays multidimensional-array casting

我有以下但它丢失了数据。我不明白为什么。此方法适用于一维数组。我100%确定dataContainer值中的对象与elementType目标匹配。

请注意,Color只是一个带有r,g,b的结构。就像你对Color的期望一样。

public static void TestFillArray()
{
    List<DataContainer> dataContainers = new List<DataContainer>();
    int[] indices = {1, 2, 3};
    dataContainers.Add(new DataContainer(indices, new Color(42, 84, 168, 255)));
    int[] dimensionSize = {2, 3, 4};

    Color[, ,] a = (Color[, ,])GetFilledArray(dataContainers, dimensionSize, typeof(Color));
    Color c = (Color)a[1, 2, 3];
    Debug.Log(c.b);
}

static Array GetFilledArray(List<DataContainer> dataContainer, int[] dimensionSize, Type elementType)
{
    int[] indices = { 1, 2, 3 };
    Array objectArray = Array.CreateInstance(typeof(object), dimensionSize);
    for (int i = 0; i < dataContainer.Count; i++)
    {
        objectArray.SetValue(dataContainer[i].value, dataContainer[i].indices);
        Color storingColor = (Color)dataContainer[i].value;
        Debug.Log(storingColor.r);

    }

    Color c3 = (Color)objectArray.GetValue(indices);
    Debug.Log(c3.r);

    Array castedArray = Array.CreateInstance(elementType, dimensionSize);
    Array.Copy(objectArray, castedArray, dataContainer.Count);
    //Now data is lost
    Color c4 = (Color)castedArray.GetValue(indices);
    Debug.Log(c4.r);
    return castedArray;
}

//Debug output:
//42
//42
//0
//0

0 个答案:

没有答案