8

我想要这样的课程:

[XmlRoot(ElementName = typeof(T).Name + "List")]
public class EntityListBase<T> where T : EntityBase, new()
{
    [XmlElement(typeof(T).Name)]
    public List<T> Items { get; set; }
}

但 typeof(T) 不能是属性参数。

我能做什么呢?

4

1 回答 1

4

您可以使用XmlAttributeOverrides- 但是 - 小心缓存和重用序列化程序实例:

static void Main()
{
    var ser = SerializerCache<Foo>.Instance;
    var list = new EntityListBase<Foo> {
        Items = new List<Foo> {
            new Foo { Bar = "abc" }
    } };
    ser.Serialize(Console.Out, list);
}
static class SerializerCache<T> where T : EntityBase, new()
{
    public static XmlSerializer Instance;
    static SerializerCache()
    {
        var xao = new XmlAttributeOverrides();
        xao.Add(typeof(EntityListBase<T>), new XmlAttributes
        {
            XmlRoot = new XmlRootAttribute(typeof(T).Name + "List")
        });
        xao.Add(typeof(EntityListBase<T>), "Items", new XmlAttributes
        {
            XmlElements = { new XmlElementAttribute(typeof(T).Name) }
        });
        Instance = new XmlSerializer(typeof(EntityListBase<T>), xao);
    }
}

(如果你不缓存和重用序列化器实例,它会泄漏程序集)

于 2012-05-26T12:36:13.763 回答