使用 XmlSerializer 序列化整数数组
-
23-08-2019 - |
题
我在尝试通过 XmlSerializer 为我正在处理的 XNA 项目序列化多维整数数组时遇到问题。我能够顺利序列化所有其他数据(布尔值、字符串,甚至颜色等)。我还看到很多人声称 XmlSerializer 本身也可以处理(一维)整数数组。多维数组是否有限制,或者这里还有其他问题吗?
这是相关代码:
int[,,] scoredata = scores; // Populated with data elsewhere
filename = Path.Combine(container.Path, "scoredata.sav");
stream = File.Open(filename, FileMode.Create);
serializer = new XmlSerializer(typeof(int[,,]));
serializer.Serialize(stream, scoredata); // This line throws the exception.
stream.Close();
我收到的异常是“System.Xml.dll 中发生了类型为‘System.InvalidOperationException’的未处理异常。生成 XML 文档时出错。”
我也尝试过使用这个数组作为结构中的成员变量(其中存储了我所有其他玩家数据),但在这样做时我也得到了相同的异常,这让我相信这不是一个简单的语法错误或类似的错误。
我是否需要重组代码以通过一维数组进行序列化,或者是否有我忽略的内容?
提前致谢!
解决方案
阅读内部异常:
- 反映类型“SomeType”时出现错误。无法序列化“System.Int32[,,]”类型的成员“SomeType.Data”,请参阅内部异常以获取更多详细信息。
- 无法序列化 System.Int32[,,] 类型的对象。不支持多维数组。
所以不行:根本不支持多维数组。您可能必须将其作为一维数组进行填充......您可以通过使用一个单独的属性来执行翻译来做到这一点:
[XmlIgnore]
public int[, ,] Data { get; set; }
[XmlElement("Data"), Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public int[] DataDto
{
get { /* flatten from Data */ }
set { /* expand into Data */ }
}
其他提示
我花了一段时间来弄清楚什么应该进入马克的get和set括号来拉平和扩大多维数组。
下面是我的用于2D阵列的解决方案。
在我的情况下,我知道在编译时,该尺寸的一个是4,所以我不必须存储(以某种方式)所述阵列的尺寸。
[XmlIgnore]
public int[,] Readings { get; set; }
[XmlArray("Readings")]
public int[] ReadingsDto {
get { return Flatten(Readings); }
set { Readings = Expand(value, 4); }
}
public static T[] Flatten<T>(T[,] arr)
{
int rows0 = arr.GetLength(0);
int rows1 = arr.GetLength(1);
T[] arrFlattened = new T[rows0 * rows1];
for (int j = 0; j < rows1; j++)
{
for (int i = 0; i < rows0; i++)
{
var test = arr[i, j];
arrFlattened[i + j * rows0] = arr[i, j];
}
}
return arrFlattened;
}
public static T[,] Expand<T>(T[] arr, int rows0)
{
int length = arr.GetLength(0);
int rows1 = length / rows0;
T[,] arrExpanded = new T[rows0, rows1];
for (int j = 0; j < rows1; j++)
{
for (int i = 0; i < rows0; i++)
{
arrExpanded[i, j] = arr[i + j * rows0];
}
}
return arrExpanded;
}
不隶属于 StackOverflow