It depends; in terms of reflection: no. You can not. But if you are talking about the attributes used by System.ComponentModel in things like data binding, you can use TypeDescriptor.AddAttributes to add additional attributes. Or other client models using custom descriptors. So it depends on the use case.
In the case of xml serialization, this becomes more interesting. Firstly, we can use interesting object models:
using System; using System.Xml.Serialization; public class MyData { [XmlAttribute] public int Id { get; set; } [XmlAttribute] public string Name { get; set; } [XmlIgnore] public bool NameSpecified { get; set; } static void Main() { var ser = new XmlSerializer(typeof(MyData)); var obj1 = new MyData { Id = 1, Name = "Fred", NameSpecified = true }; ser.Serialize(Console.Out, obj1); Console.WriteLine(); Console.WriteLine(); var obj2 = new MyData { Id = 2, Name = "Fred", NameSpecified = false }; ser.Serialize(Console.Out, obj2); } }
The bool {name}Specified {get;set;} pattern (along with bool ShouldSerialize{name}() ) is recognized and used to control which elements to include.
Another alternative is to use a non-default ctor:
using System; using System.Xml.Serialization; public class MyData { [XmlAttribute] public int Id { get; set; } public string Name { get; set; } static void Main() { var obj = new MyData { Id = 1, Name = "Fred" }; XmlAttributeOverrides config1 = new XmlAttributeOverrides(); config1.Add(typeof(MyData),"Name", new XmlAttributes { XmlIgnore = true}); var ser1 = new XmlSerializer(typeof(MyData),config1); ser1.Serialize(Console.Out, obj); Console.WriteLine(); Console.WriteLine(); XmlAttributeOverrides config2 = new XmlAttributeOverrides(); config2.Add(typeof(MyData), "Name", new XmlAttributes { XmlIgnore = false }); var ser2 = new XmlSerializer(typeof(MyData), config2); ser2.Serialize(Console.Out, obj); } }
Note that if you use this second approach, you need to cache the serializer instance, as it emits an assembly every time you do it. I find the first approach easier ...
Marc gravell
source share