如何序列化聚合其他自定义对象的自定义对象

时间:2013-12-30 09:10:22

标签: c# .net serialization

我正在尝试将自定义对象序列化为文件。 我尝试过很多东西,但没有人工作,我一定错过了一件事。

这是问题所在。

我有一个用于存储我的对象的单例类。 这是代码:

using DataLibrary.Model.Tests;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using testsPsychotechniques.View;

namespace testsPsychotechniques.Model
{
    [Serializable()]
    public class testSaver : ISerializable
    {
        private String lastName;
        private String firstName;
        private List<ITest> tests;


        public static testSaver Instance
        {
            get
            {
                return Nested.instance;
            }
        }

        public void addTest(ITest test)
        {
            tests.Add(test);
        }

        public Boolean save()
        {
            try
            {
                FileStream file = File.Open(".\\result.data",
                                            FileMode.Create,
                                            FileAccess.ReadWrite,
                                            FileShare.None);

                XmlSerializer serializer = new XmlSerializer(typeof(testSaver));
                serializer.Serialize(file, testSaver.Instance);
                file.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        private testSaver()
        {
            this.firstName = Identification.firstName;
            this.lastName = Identification.lastName;
            this.tests = new List<ITest>();
        }


        private class Nested
        {
            internal static readonly testSaver instance = new testSaver();
        }

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("lastName", this.lastName);
            info.AddValue("firstName", this.firstName);
            info.AddValue("testsResults", this.tests);
        }
    }
}

现在真正的问题是:

当我调用save方法时,在生成的xml文件中我只有这个数据:

<?xml version="1.0"?>
<testSaver xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />

实现ITest接口的类都标记为可序列化并且具有方法getObjectData。

另一个提示是从不使用函数getObjectData。

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

XmlSerializer不使用[Serializable]属性或ISerializable界面。

这里有两个选项:

  1. 继续使用XmlSerializer,在这种情况下,您需要公共属性和公共noarg构造函数。
  2. XmlSerializer更改为SoapFormatter并继续使用[Serializable]ISerializable,您不需要两者。
  3. 这实际上取决于您希望Xml的格式,以及您是否更喜欢使用属性或代码来控制序列化。我会选择选项1,因为它通常更简单。

相关问题