Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 874
Rzassar Avatar asked May 26 '12 12:05

Rzassar


People also ask

How do you determine if a class has a particular attribute?

The same you would normally check for an attribute on a class. Here's some sample code. typeof(ScheduleController) . IsDefined(typeof(SubControllerActionToViewDataAttribute), false);

What is parameter attribute in C#?

The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are: One of the following types: bool , byte , char , double , float , int , long , sbyte , short , string , uint , ulong , ushort . The type object . The type System.

What is custom attribute in C#?

Attributes are used to impose conditions or to increase the efficiency of a piece of code. There are built-in attributes present in C# but programmers may create their own attributes, such attributes are called Custom attributes. To create custom attributes we must construct classes that derive from the System.


1 Answers

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)

like image 189
Marc Gravell Avatar answered Oct 16 '22 08:10

Marc Gravell