繁体   English   中英

如何在 C# 中序列化/反序列化 object 矩阵到 xml 或从 xml?

[英]How to serialize/deserialize an object matrix to/from xml in C#?

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

[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:Object 引用未设置为 object 的实例。

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:感谢您的尝试,但没有任何效果,所以我将重写代码以使用列表而不是矩阵。

您可以尝试像这样更改您的设置:

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

您可能不想使用游戏 object 中的高度和宽度属性,因为您需要假设在此属性之前设置了这些属性。 还不如自己计算。 当您使用它时,不妨也更改 get,然后丢弃高度/宽度,或更改它们以实际拉取网格的当前宽度/高度:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM