【发布时间】: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