0

我有以下课程:

[Serializable]

public class SerialAssassin
{
    public Hero hero;
    public Point heroPB;
    public Boss boss;
    public Point bossPB;
    public Attack attack;
    public Point attackPB;
    public HPMeter bossHP;
    public Point bossHPPB;
    public PPMeter heroPP;
    public Point heroPPPB;

    public Rectangle bossRect;
    public Rectangle attackRect;

    public int heroState;
    public int stepRate;
    public int attackDirection;
    public int attackLoop;
    public int contadorPaso;
    public int contadorPasoBoss;
    public int bossTop, bossLeft;
    public int bossState;
    public int bossHealth;
    public int bossHPCap;
    public int opa;
    public int battlesWon;
    public int mainBossCounter;
    public int ppleft;
    public bool paso;
    public bool inStadium;
    public bool fading;
    public bool fightingMainBoss;
    public bool fainted;
    public string currentPokemon;
}

我在从 XML 读取数据时遇到问题,其编写如下:

XmlSerializer serializer = new XmlSerializer(typeof(SerialAssassin));
TextWriter textWriter = new StreamWriter(@"..\..\Resources\saveState.xml");
serializer.Serialize(textWriter, serial);
textWriter.Close();

从那里,我不太清楚如何读取数据。再加上 XML 不序列化 Hero、Boss、Attack、HPMeter、PPMeter 的对象这一事实。

英雄等级:

public class Hero
    {

        int state = 0;
        int x, y;
        string path;
        Image img;


        //methods
    }

如果您能向我解释如何加载这些对象/基元然后使用它们,我将不胜感激。

4

2 回答 2

3

IIRC,XmlSerializer检查属性,而不是字段。(我认为它可以使用公共字段,但无论如何你真的应该切换到属性)此外,类不需要标记Serializable. (Serializable用于其他,如二进制和 SOAP 序列化程序)

将您的字段替换为具有公共 getter 和 setter 的属性。此外,请确保您的其他类(例如HeroPointBoss)也都可以根据XmlSerializer的规则进行序列化:

public class SerialAssassin
{
    public Hero hero { get; set; }
    public Point heroPB { get; set; }
    public Boss boss { get; set; }
    public int heroState { get; set; }
    ...

要反序列化,请使用其Deserialize方法(http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.deserialize.aspx):

Stream xmlInputStream = ... //get your file stream, or TextReader, or XmlReader
XmlSerializer deserializer = new XmlSerializer(typeof(SerialAssassin));
SerialAssassin assassin = (SerialAssassin)deserializer.Deserialize(xmlInputStream)

编辑:查看您的示例Hero类,它没有序列化它的任何值,因为您已将它们全部声明为私有。改为公开它们。

public class Hero
{
    public int state {get; set; }
    public int x { get; set; }
    public int y { get; set; }
    public string path { get; set; }

    [XmlIgnore]
    public Image img { get; set; }
}

我怀疑这不会Image是可序列化的,因此您可能想要存储图像的文件路径(或其他一些识别信息),以便您可以保存/加载它。将指示忽略该属性,使其在序列化/反序列化期间不会失败。[XmlIgnore]XmlSerializer

于 2012-12-18T21:48:46.920 回答
2
XmlSerializer serializer = new XmlSerializer(typeof(SerialAssassin));
SerialAssassin assassin;

using(var reader = File.OpenText(@"..\..\Resources\saveState.xml"))
{
   assassin = (SerialAssassin)serializer.Deserialize(reader);
}
于 2012-12-18T21:48:17.957 回答