传递一个Type作为属性参数

时间:2012-05-26 12:04:46

标签: 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; }
}

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

我该怎么做?

1 个答案:

答案 0 :(得分: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);
    }
}

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