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?
The same you would normally check for an attribute on a class. Here's some sample code. typeof(ScheduleController) . IsDefined(typeof(SubControllerActionToViewDataAttribute), false);
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With