如何在C#中的xml中对对象矩阵进行序列化/反序列化?

我有一个任务来保存和加载扫雷板。我在保存电路板矩阵时遇到问题。这些是我的扫雷属性:

[XmlIgnore]
public Tile[,] Grid { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int NumberOfMines { get; set; }

瓷砖属性:

public int X { get; set; }
public int Y { get; set; }
public int NeighbourMines { get; set; }
public bool IsMine { get; set; }
public bool IsRevealed { get; set; }
public bool Isflagged { get; set; }

我尝试过这样的事情:

public List<Tile> ListFromMatrix
{
    get
    {
        List<Tile> temp = new List<Tile>(Height * Width);
        for (int i = 0; i < Height; i++)
            for (int j = 0; j < Width; j++)
                temp.Add(Grid[i,j]);
        return temp;
    }
    set
    {
        //Grid = new Tile[Height,Width];
        int it = 0;
        for (int i = 0; i < Height; i++)
            for (int j = 0; j < Width; j++)
                Grid[i,j] = value[it++];
    }
}

保存到文件中效果很好,但是从文件中加载会导致异常。而且我真的不知道如何调试它,因为在以下位置抛出了异常:

//this.Game is the Minesweeper reference in the main form
this.Game = (Game)xs.Deserialize(fileStream);

感谢您的帮助!

编辑:这是个例外

System.InvalidOperationException:'XML文档中存在错误(7,4)。 内部异常1:NullReferenceException:对象引用未设置为对象的实例。

EDIT2:保存代码

SaveFileDialog sfd = new SaveFileDialog();
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                using (FileStream fs = new FileStream(sfd.FileName,FileMode.Create))
                {
                    XmlSerializer xs = new XmlSerializer(typeof(Game));
                    xs.Serialize(fs,this.Game);
                }
            }

EDIT3:这是xml内容https://pastebin.com/0vkxQC5A

EDIT4:感谢您的尝试,但此操作无济于事,因此我将重写代码以使用列表而不是矩阵。

suijianzhi 回答:如何在C#中的xml中对对象矩阵进行序列化/反序列化?

您可以尝试如下更改设置:

set
{
    var height = value.Max(t=>t.Y);
    var width = value.Max(t=>t.X);
    Grid = new Tile[height,width];
    foreach(var tile in value)
    {
      Grid[tile.Y,tile.X]=tile;
    }
}

您可能不想使用游戏对象的height和width属性,因为那样的话,您需要假设在此属性之前设置了height和width属性。最好自己计算一下。而当您使用它时,不妨先进行更改,然后丢弃“高度/宽度”,或者更改它们以实际拉动网格的当前宽度/高度:

get
{
    var temp = new List<Tile>(Grid.Length);
    for (int i = 0; i < Grid.GetLength(0); i++)
        for (int j = 0; j < Grid.GetLength(1); j++)
            temp.Add(Grid[i,j]);
    return temp;
}
,

似乎错误在于对属性ListFromMatrix进行反序列化。

public List<Tile> ListFromMatrix {get; set;}


// when it comes time to serialize
ListFromMatrix = CreateList();
using (FileStream fs = new FileStream(sfd.FileName,FileMode.Create))
{
    XmlSerializer xs = new XmlSerializer(typeof(Game));
    xs.Serialize(fs,this.Game);
}

private List<Tile> CreateList()
{
    var temp = new List<Tile>(Height * Width);
    for (int i = 0; i < Height; i++)
        for (int j = 0; j < Width; j++)
            temp.Add(Grid[i,j]);
    return temp;
}
本文链接:https://www.f2er.com/3102136.html

大家都在问