C#Xml序列化和Memento模式 - 序列化程序无法保存对象

时间:2016-09-01 19:39:53

标签: c# xml serialization xml-serialization

我正在尝试学习如何在c#中将对象保存到文件中。我正在尝试使用Xml序列化和Memento模式。我要保存的对象是“看守”类型。这是它的样子:

public class Memento
{
    public int prop1 { get;private set; }
    public String prop2 { get;private set; }
    public int SomeClassProp { get; private set; }
    public Memento(int p1, String p2, SomeClass sc)
    {
        this.prop1 = p1; this.prop2 = p2; this.SomeClassProp = sc.SomeClassProp1;
    }




}
public class Caretaker
{
    private Memento _memento;

    // Gets or sets memento
    public Memento Memento
    {
        set { _memento = value; }
        get { return _memento; }
    }
}

串行器代码(从堆栈溢出复制):

  public void SerializeObject<T>(T serializableObject, string fileName)
    {
        if (serializableObject == null) { return; }

        try
        {
            XmlDocument xmlDocument = new XmlDocument();
            XmlSerializer serializer = new                  XmlSerializer(serializableObject.GetType());
            using (MemoryStream stream = new MemoryStream())
            {
                serializer.Serialize(stream, serializableObject);
                stream.Position = 0;
                xmlDocument.Load(stream);
                xmlDocument.Save(fileName);
                stream.Close();
            }
        }
        catch (Exception ex)
        {
            //Log exception here
        }
    }


    /// <summary>
    /// Deserializes an xml file into an object list
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public T DeSerializeObject<T>(string fileName)
    {
        if (string.IsNullOrEmpty(fileName)) { return default(T); }

        T objectOut = default(T);

        try
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(fileName);
            string xmlString = xmlDocument.OuterXml;

            using (StringReader read = new StringReader(xmlString))
            {
                Type outType = typeof(T);

                XmlSerializer serializer = new XmlSerializer(outType);
                using (XmlReader reader = new XmlTextReader(read))
                {
                    objectOut = (T)serializer.Deserialize(reader);
                    reader.Close();
                }

                read.Close();
            }
        }
        catch (Exception ex)
        {
            //Log exception here
        }

        return objectOut;
    }

问题在于:

  

的XmlSerializer(serializableObject.GetType());

这是抛出异常的地方,结果是不创建文件。我猜我要保存的对象类型有问题,对吧?你能以某种方式帮助我吗?

编辑: 串行器用法:

c.Memento = this.CreateMemento();
SerializeObject<Caretaker>(c, "savedObj");

0 个答案:

没有答案