传递一个Type作为属性参数

Rza*_*sar 9 c# generics attributes

我想要这样的课:

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

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

我该怎么做?

Mar*_*ell 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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