【问题标题】:Serialize collection of base class to XML dynamically将基类的集合动态序列化为 XML
【发布时间】:2014-04-11 09:56:16
【问题描述】:

哎呀,

我想序列化和对象,看起来像这样:

public class Wrapper
{
    [XmlArray("Entities"), XmlArrayItem("Entity")]
    public List<Base> Entities { get; set; }
}

我想让应用程序尽可能灵活,因此不能在 XmlArrayItem 属性中手动设置派生类类型,我该如何动态地做到这一点,即让序列化程序了解所有派生类。

顺便说一句,我已经有一个类可以获取所有直接派生的类型,例如 BaseDerived.DerivedClassesXmlSerializer cs = new XmlSerializer(this.GetType(),BaseDerived.DerivedClasses); 不起作用...

有什么想法吗?

【问题讨论】:

    标签: c# generics serialization xml-serialization


    【解决方案1】:

    找到一个灵魂,在序列化过程中你几乎可以直接插入项目属性

    所以首先你要收集类似的属性

        XmlAttributeOverrides xOver = new XmlAttributeOverrides();
        XmlAttributes xAttrs = new XmlAttributes();
        foreach (var cls in BaseDerived.DerivedClasses)
        {
            var attr = new XmlArrayItemAttribute(cls);
            xAttrs.XmlArrayItems.Add(attr);
        }
        xOver.Add(this.GetType(), BaseDerived.GetMemberName((Wrapper x) => x.Entities), xAttrs);
    

    顺便说一句:

    public static string GetMemberName<T, TValue>(Expression<Func<T, TValue>> memberAccess)
    {
        return ((MemberExpression)memberAccess.Body).Member.Name;
    }
    

    然后你只是在序列化中提到它:

        XmlSerializer cs = new XmlSerializer(this.GetType(), xOver);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多