【问题标题】:Multidimensional Array Casting Runtime Error ---> unable to cast object of type 'System.Object[,]' to type 'System.String多维数组转换运行时错误 ---> 无法将“System.Object[,]”类型的对象转换为“System.String”类型
【发布时间】:2013-01-02 16:54:06
【问题描述】:

我在将多维对象数组 (object[,]) 简单转换为新数据类型 (string[,]) 以进行日志记录时遇到问题。该格式是一个动态二维数组,有许多列和行,但不能很好地适应框架中提供的通用集合对象之一。在整个过程中,我只会将它强输入为string[,],但我需要对象数组的灵活性,因为在某些情况下我需要使用不同的数据类型。

private List<KeyValuePair<string, object>> _dataList = new List<KeyValuePair<string, object>>();
private object[,] _dataArray;

public List<KeyValuePair<string, object>> RetrieveHistoricalData()
{

...

//Calling Method (for explaination and context purposes)

_log.Log ("\r\nRetrieveHistoricalData", "_dataList.Count: " + _dataList.Count);
_dataList.ForEach(dli => _log.Log ("\r\nRetrieveHistoricalData", "_dataList: " 
    + dli.Key + ((object[,])dli.Value)
    .CastTwoDimensionalArray<string>()
    .TwoDimensionalArrayToString()));

...

}

... 根据 Jon Skeet 的建议添加了一个扩展方法 ...

internal static T[,] CastTwoDimensionalArray<T>(this object[,] dataArray)
{
    int rows = dataArray.GetLength(0);
    int columns = dataArray.GetLength(1);
    T[,] returnDataArray = new T[rows, columns];
    for (int row = 0; row < rows; row++)
    {
        for (int column = 0; column < columns; column++)
        {
            returnDataArray[row, column] =
                      (T)Convert.ChangeType(dataArray[row, column], typeof(T));
        }
    }
    return returnDataArray;
}

... 这是我自己的补充(仅包括在内,因为它在我正在执行的行中) ...

internal static string TwoDimensionalArrayToString<T>(this T[,] dataArray)
{
    int rows = dataArray.GetLength(0);
    int columns = dataArray.GetLength(1);
    string returnString = "";
    for (int row = 0; row < rows; row++)
    {
        for (int column = 0; column < columns; column++)
        {
            returnString = returnString + "[" + row + "," + column + "] =>" + dataArray[row,column]+ " ;  ";
        }
    }

    return returnString;
}

我已经从第一篇文章中编辑了上面的代码,但是在尝试在通用扩展方法中将 System.Double 转换为 System.String 时,我仍然收到 System.InvalidCastException。我正在研究一种通过类型反射添加一些异常以消除剩余问题的简单方法。

谢谢。

【问题讨论】:

  • 你好像没有提到语言。
  • _dataList的定义是什么?
  • 对不起,我刚刚添加了 _dataList 定义。
  • 谢谢,但我仍然无法确定您插入 _dataList 的对象是什么类型 :) 这将允许我们检查您对 string[,] 的强制转换失败的原因。
  • Ameen,我实际上在原始帖子中错误地陈述了该对象。我现在已经更正了它以表明它实际上是一个对象 [,],而不是一个字符串 [,]。

标签: c# multidimensional-array casting type-conversion


【解决方案1】:

编辑:您只能从 object[,] 转换为 string[,] 如果涉及的数组确实最初是 string[,]。例如,这很好:

object[,] o = new string[,]
{
    { "x", "y" },
    { "a", "b" }
};
string[,] x = (string[,]) o;

...但这不是:

object[,] o = new object[,]
{
    { "x", "y" },
    { "a", "b" }
};
string[,] x = (string[,]) o; // Bang!

即使数组的每个元素 都是字符串,它仍然不是字符串数组。在后一种情况下,您需要编写自己的代码来创建新的数组对象并执行元素转换。例如,您可以使用以下通用方法来转换每个元素:

using System;

class Test
{
    static void Main()
    {
        object[,] o = new object[,]
        {
            { "x", "y" },
            { "a", "b" }
        };
        string[,] x = Cast2D<string>(o);
        Console.WriteLine(x[1, 1]); // "b"
    }

    static T[,] Cast2D<T>(object[,] input)
    {
        int rows = input.GetLength(0);
        int columns = input.GetLength(1);
        T[,] ret = new T[rows, columns];
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < columns; j++)
            {
                ret[i, j] = (T) input[i, j];
            }
        }
        return ret;
    }        
}

在你的情况下,你可能想要:

object[,] array = (object[,]) financialDataObject;
string[,] financialData = Cast2D<string>(array);

【讨论】:

  • 感谢您的建议。实际上,我不得不返回并更改我声称原始字段是字符串 [,] 的第一个语句。它实际上是一个 object[,] 的起源。我回去查看了我的代码的其他部分,并注意到我期望收到无数不同类型的历史数据,我必须对其进行转换,所以我可能不得不在里面编写一堆转换逻辑像您上面发布的那样的通用方法。
  • Jon:.NET 1 的“疯狂”数组协方差似乎适用于二维数组。我刚刚成功运行了这段代码:string[,] arr1 = { { "Hello", "this", }, { "is", "working", }, }; object[,] arr2 = arr1; Console.WriteLine(arr2[1, 1]);
  • @JeppeStigNielsen:你完全正确。我发誓我在发布之前尝试过,编译器告诉我没有这样的转换可用。不知道我现在在做什么。将编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-17
  • 2014-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多