用于反序列化二维数组的Xml反序列化器

时间:2013-12-16 22:11:57

标签: c# xml serialization multidimensional-array deserialization

我有一个关于反序列化数组的问题(int []) 我有一个数组int[*,*],我需要序列化和反序列化它。如何使用XMLSerializer?

    int[,] B = new int[2,5];        
    public int[,] XMLIntArray
    {
        set { B = value; }
        get { return B; }
    }

2 个答案:

答案 0 :(得分:1)

不幸的是,XmlSerializer或DataContractSerializer不支持多维数组序列化,唯一的方法(非人类可读)是使用二进制序列化,如本例所示

   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; 
    }  

答案 1 :(得分:0)

你不能序列化int [,]但你可以序列化int [] []。在序列化数组之前,只需将其转换为:

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]; 
}