使用XmlSerializer序列化整数数组

我正在尝试通过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(); 

我收到的exception是“System.Xml.dll中发生类型’System.InvalidOperationException’的未处理exception。生成XML文档时出错。”

我也尝试将这个数组用作结构中的成员变量(我存储了所有其他玩家数据),但是当我这样做的时候我得到同样的exception,这让我相信它不是简单的语法错误或类似的东西。

我是否需要重新构建我的代码以通过单维数组进行序列化,或者我有什么东西可以忽略?

提前致谢!

阅读内部exception:

  • 反映类型’SomeType’时出错。 无法序列化’System.Int32 [,,]’类型的成员’SomeType.Data’,请参阅内部exception以获取更多详细信息。
  • 无法序列化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 */ } } 

我花了一段时间才弄清楚应该进入Marc的内容并设置括号以展平和扩展多维数组。

这是我的2Darrays解决方案。

在我的例子中,我知道在编译时其中一个维度是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[,] 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[] 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; }