我有一个任务来保存和加载扫雷板。我在保存电路板矩阵时遇到问题。这些是我的扫雷属性:
[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:感谢您的尝试,但此操作无济于事,因此我将重写代码以使用列表而不是矩阵。