问题
I have a problem about deserialize an array ( int[,])
I have an array int[*,*] and i need to serialize and deserialize it. How to do it with XMLSerializer??
int[,] B = new int[2,5];
public int[,] XMLIntArray
{
set { B = value; }
get { return B; }
}
回答1:
Unfortunately multidimensional arrays serialization are not supported by XmlSerializer or DataContractSerializer the only way (not human readable) is to use binary serialization like in this example
public static void Main()
{
int[,] B = new int[2, 5];
B[0, 0] = 5;
B[0, 1] = 3;
B[0, 2] = 5;
DeepSerialize<int[,]>( B,"test3");
int[,] des= DeepDeserialize<int[,]>("test3");
}
public static void DeepSerialize<T>(T obj,string fileName)
{
// MemoryStream memoryStream = new MemoryStream();
FileStream str = new FileStream(fileName, FileMode.Create);
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(str, obj);
str.Close();
}
public static T DeepDeserialize<T>(string fileName)
{
// MemoryStream memoryStream = new MemoryStream();
FileStream str = new FileStream(fileName, FileMode.Open);
BinaryFormatter binaryFormatter = new BinaryFormatter();
T returnValue = (T)binaryFormatter.Deserialize(str);
str.Close();
return returnValue;
}
回答2:
You cannot serialze a int[,] but you can serialize a int[][]. Before serializing your array, just convert it like that:
var my2dArray = new int[2,5];
var myJaggedArray = new int [2][];
for(int i = 0 ; i < my2DArray.GetLength(0) ; i ++)
{
myJaggedArray[i] = new int[my2DArray.GetLength(1)];
for(int j = 0 ; j < my2DArray.GetLength(1) ; j ++)
myJaggedArray[i][j] = my2DArray[i,j];
}
来源:https://stackoverflow.com/questions/20622005/xml-deserializer-to-deserialize-2-dimensional-array