XML Serializer:为什么反序列化在我的情况下不起作用?

时间:2009-11-21 14:53:17

标签: c# xml-serialization

人。我使用XMLSerializer来保存和恢复程序选项。这是代码:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace XMLAsk
{
    class Test
    {
        public static string ConfigFileName = "C:\\Work\\TMP\\Config.xml";

        public static void Main()
        {

            MyOptions myOptions = new MyOptions();
            myOptions.Title = "Hello, world!";
            myOptions.Rating = 15;

            SerializeToXML(myOptions);

            MyOptions myOptions2 = new MyOptions();
            DeserializeFromXML(myOptions2);

            MessageBox.Show(myOptions2.Title);


        }

        public static void SerializeToXML(MyOptions myOptions)
        {

            XmlSerializer serializer = new XmlSerializer(typeof(MyOptions));
            TextWriter textWriter = new StreamWriter(ConfigFileName);
            serializer.Serialize(textWriter, myOptions);
            textWriter.Close();

        }

        public static void DeserializeFromXML(MyOptions myOptions2)
        {

            XmlSerializer deserializer = new XmlSerializer(typeof(MyOptions));
            TextReader textReader = new StreamReader(ConfigFileName);
            myOptions2 = (MyOptions)deserializer.Deserialize(textReader);
            textReader.Close();

        }
    }

    public class MyOptions
    {


        private string title;
        private int rating;

        public string Title
        {
            get { return title;  }
            set { title = value; }
        }

        public int Rating
        {
            get { return rating; }
            set { rating = value;}
        }

   }

}

序列化确实有效。我得到以下xml文件(Config.xml):

<?xml version="1.0" encoding="utf-8" ?> 
- <MyOptions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Title>Hello, world!</Title> 
  <Rating>15</Rating> 
  </MyOptions>

但反序列化似乎不起作用。例如,当我使用 MessageBox.Show(myOptions2.Title); (参见上面的代码)显示其中一个选项时,我得到一个空字符串。

为什么呢?我的代码出了什么问题?

1 个答案:

答案 0 :(得分:4)

myOptions2 = (MyOptions)deserializer.Deserialize(textReader);

您需要返回该对象。或者使用ref参数。