c# – 如何将泛型类序列化为XML?

只要通用字段Object的实际类型包含在XmlElement属性列表中,就可以按照预期将以下类的对象序列化为
XML

public class SerializedObject<T> : Serializable where T : Serializable
{
    [System.Xml.Serialization.XmlElement(Type = typeof(Weapon))]
    [System.Xml.Serialization.XmlElement(Type = typeof(Armor))]
    [System.Xml.Serialization.XmlElement(Type = typeof(QuestItem))]
    public T Object;

    public string ObjectId;
    public int ID;

    public SerializedObject() { }

    public SerializedObject(T _object)
    {
        Object = _object;
        ID = Object.Id;
        ObjectId = Object.ObjectId;
    }
}

问题是:

如何序列化此类的对象,包括通用字段Object,而不指定XmlElement属性中T的所有可能类型?

最佳答案 我也碰到了这个.我做的是创建一个包装类:

public static XmlDocument SerializeToXmlDocument<XmlEntity>(XmlEntity o)
{
    XmlDocument xdoc;
    SerializeWrapper<XmlEntity> wrapper = new SerializeWrapper<XmlEntity>();
    wrapper.XmlObject = o;

    XmlSerializer xs = new XmlSerializer(wrapper.GetType());
    using (MemoryStream ms = new MemoryStream())
    {
        xs.Serialize(ms, wrapper);
        xdoc = new XmlDocument();
        ms.Position = 0;
        xdoc.Load(ms);
    }

    return xdoc;
}

这是用于包装对象的类

[XmlRoot("Root")]
public class SerializeWrapper<TObject>
{
    [XmlAttribute()]
    public string Name { get; set; }

    public TObject XmlObject { get; set; }
}

现在,您可以将其称为:

Weapon weapon = new Weapon()
var xdoc = SerializeToXmlDocument<Weapon>(weapon);
点赞