代码之家  ›  专栏  ›  技术社区  ›  Racoon

XML序列化程序:在我的例子中,为什么反序列化不起作用?

  •  1
  • Racoon  · 技术社区  · 15 年前

    伙计们。我使用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(myopitions2.title); (见上面的代码),然后我得到一个空字符串。

    为什么?我的代码怎么了?

    1 回复  |  直到 15 年前
        1
  •  4
  •   leppie    15 年前
    myOptions2 = (MyOptions)deserializer.Deserialize(textReader);
    

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