簡體   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