Rzassar
Rzassar

Reputation: 2282

pass a Type as an attribute argument

i want to have some class like this:

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

but typeof(T) cannot be attribute argument.

what can i do instead?

Upvotes: 8

Views: 1759

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062492

You could use XmlAttributeOverrides - BUT - be careful to cache and re-use the serializer instance:

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);
    }
}

(if you don't cache and re-use the serializer instance, it will leak assemblies)

Upvotes: 4

Related Questions