1

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

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

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
4

0 回答 0