[英]Serializing an array of integers using 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();
我收到的例外是
System.Xml.dll 中發生類型為“System.InvalidOperationException”的未處理異常。 生成 XML 文檔時出錯。
我還嘗試將此數組用作結構中的成員變量(存儲我所有其他玩家數據的位置),但是在以這種方式做事時我也遇到了相同的異常,這讓我相信它不是一個簡單的語法錯誤或類似的錯誤。
我是否需要重構我的代碼以通過單維數組進行序列化,或者我忽略了什么?
提前致謝!
閱讀內部異常:
所以不:根本不支持多維數組。 您可能需要將它作為單維數組填充……您可以通過擁有一個單獨的屬性來進行翻譯來做到這一點:
[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 的 get 和 set 大括號中加入什么來展平和擴展多維數組。
這是我的二維數組解決方案。
就我而言,我在編譯時知道其中一個維度是 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.