【问题标题】:How do I serialize a class inherited from List<T> with custom parameter to XML?如何使用自定义参数将继承自 List<T> 的类序列化为 XML?
【发布时间】:2016-10-05 10:55:16
【问题描述】:

我有一个继承自 List 的类

[Serializable]
public class ListWithVersion<T> : List<T>
{
    [XmlElement(ElementName = "version")]
    public int version;

    public ListWithVersion(IEnumerable<T> collection) : base(collection)
    {
    }

    public ListWithVersion() : base()
    {

    }
}

我像这样将它序列化为 XML

ListWithVersion<Chapter> lwv = new ListWithVersion<Chapter>();
        Chapter chapter = new Chapter();
        chapter.dialogs = new List<Dialog>();
        lwv.version = 1;
        lwv.Add(chapter);

        Serialize("lwv.xml", typeof(ListWithVersion<Chapter>), extraTypes, lwv);

    private void Serialize(string name, Type type, Type[] extraTypes, object obj)
    {
        try
        {
            var serializer = new XmlSerializer(type, extraTypes);
            using (var fs = new FileStream(GetPathSave() + name, FileMode.Create, FileAccess.Write))
            {
                serializer.Serialize(fs, obj);
            }
        }
        catch (XmlException e)
        {
            Debug.LogError("serialization exception, " + name + " Message: " + e.Message);
        }
        catch (System.Exception ex)
        {
            Debug.LogError("exc while ser file '" + name + "': " + ex.Message);
            System.Exception exc = ex.InnerException;
            int i = 0;
            while (exc != null)
            {
                Debug.LogError("inner " + i + ": " + exc.Message);
                i++;
                exc = exc.InnerException;
            }
        }
    }

但 XML 文件不包含版本参数。

<?xml version="1.0" encoding="windows-1251"?>
<ArrayOfChapter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Chapter id="0">
    <dialogs />
  </Chapter>
</ArrayOfChapter>

(version="1.0" 不是我的参数)

我尝试过 XmlAttribute 而不是 XmlElement,也尝试过原始

public int version;

在 XML 中获取版本参数没有任何帮助。

那我该如何解决呢?

【问题讨论】:

    标签: c# xml unity3d


    【解决方案1】:

    您将无法直接执行此操作,因为 XmlSerializerICollection&lt;T&gt; 对象进行了特殊处理(正如您所注意到的),它几乎忽略了该类并仅序列化其内容。两种选择:

    • 实现IXmlSerializable 并进行自己的序列化。
    • 修改您的类,使其具有List&lt;T&gt; 类型的成员,而不是从它继承。

    编辑:我会在这里回答您的评论,因为使用格式化文本更容易。您可以这样做,但这可能需要混合使用这两种方法。

    1. 在您的班级中有一个私人List&lt;T&gt;
    2. 让您的班级实现IList&lt;T&gt; 而不是List&lt;T&gt;。使用私有列表实现所有接口成员,例如:

    public void Add(T item) => this.list.Add(item);
    
    public void Clear() => this.list.Clear();
    
    [...]
    
    1. 实现IXmlSerializable - 首先编写您自己的变量,然后使用私有列表输出其他所有内容。

    【讨论】:

    • 我能不能先写下version参数的值,然后使用默认ICollection的实现?
    • @user2686299 更新了我的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    相关资源
    最近更新 更多