use*_*079 3 c# wpf serialization deserialization
对不起,这个问题似乎很愚蠢.我已经研究了一些关于这个主题的网页,但我不确定它们对我的问题有多重要.我有一个2D地图设计师.我想保存地图,以便我可以加载它并在其上玩游戏.我对序列化很新,我想知道我应该研究哪些文档,以及是否有人可以指向一些与我的序列化任务相关的网页.这是数据结构:
public class ModelMap
{
public ModelMap()
{
this.cellBgImage = new Image();
this.exitImage = new Image();
this.theseus = new Image();
this.minotaur = new Image();
}
public int rows { get; set; }
public int cols { get; set; }
public int boardXPos { get; set; }
public int boardYPos { get; set; }
public int myCellSize { get; set; }
public Image cellBgImage { get; set; }
public string HorizontalWallSource { get; set; }
public string VerticalWallSource { get; set; }
public Image minotaur { get; set; }
public Image theseus { get; set; }
public Image exitImage { get; set; }
public string exitCellPlacement { get; set; }
public int myWidth { get; set; }
public int myHeight { get; set; }
private List<Cell> m_cells = new List<Cell>();
public List<Cell> myCells
{
get
{
return m_cells;
}
set
{
m_cells = value;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
细胞类:
public class Cell
{
public Cell(int col, int row, CellSide rightWall, CellSide bottomWall, ModelMap map)
{
this.myColumn = col;
this.myRow = row;
this.myRightWall = rightWall;
this.myBottomWall = bottomWall;
this.myMap = map;
}
public Cell(int col, int row, CellSide rightWall, CellSide bottomWall, ModelMap map, Image bgImage)
{
this.myColumn = col;
this.myRow = row;
this.myRightWall = rightWall;
this.myBottomWall = bottomWall;
this.myMap = map;
this.myBgImage = bgImage;
}
public ModelMap myMap { get; set; }
public Image myBgImage { get; set; }
public bool hasMinotaur { get; set; }
public bool hasTheseus { get; set; }
public bool isExit { get; set; }
public int mySize { get; set; }
public CellSide myRightWall { get; set; }
public CellSide myBottomWall { get; set; }
public int myColumn { get; set; }
public int myRow { get; set; }
}
public class CellSide
{
public CellSide(int hasWall, bool highlighted)
{
this.hasWall = hasWall;
this.isHighlighted = highlighted;
}
public bool isHighlighted { get; set; }
public int hasWall { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢.
阅读有关标准.NET序列化和XML序列化示例的信息.您需要进行一些更改才能使这些类的序列化成为可能:
Cell并且CellSide必须有无参数构造函数,Image(或者说它的实现)不能直接序列化,但你可以做一些解决方法(比如在这个问题中)或者只是序列化图像的文件路径并在反序列化后加载它们然后,您可以将对象序列化为XML文件:
var map = new ModelMap();
...
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(ModelMap));
using (var writer = new StreamWriter(@"e:\test.xml"))
{
serializer.Serialize(writer, map);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7616 次 |
| 最近记录: |