Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

c# - Can I add attributes to an object property at runtime?

For example I want to remove or change below property attributes or add a new one. Is it possible?

[XmlElement("bill_info")]
[XmlIgnore]
public BillInfo BillInfo
{
  get { return billInfo; }
  set { billInfo = value; }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

(edit - I misread the original question)

You cannot add actual attributes (they are burned into the IL); however, with XmlSerializer you don't have to - you can supply additional attributes in the constructor to the XmlSerializer. You do, however, need to be a little careful to cache the XmlSerializer instance if you do this, as otherwise it will create an additional assembly per instance, which is a bit leaky. (it doesn't do this if you use the simple constructor that just takes a Type). Look at XmlAttributeOverrides.

For an example:

using System;
using System.Xml.Serialization;
 public class Person
{
    static void Main()
    {
        XmlAttributeOverrides overrides = new XmlAttributeOverrides();
        XmlAttributes attribs = new XmlAttributes();
        attribs.XmlIgnore = false;
        attribs.XmlElements.Add(new XmlElementAttribute("personName"));
        overrides.Add(typeof(Person), "Name", attribs);

        XmlSerializer ser = new XmlSerializer(typeof(Person), overrides);
        Person person = new Person();
        person.Name = "Marc";
        ser.Serialize(Console.Out, person);
    }
    private string name;
    [XmlElement("name")]
    [XmlIgnore]
    public string Name { get { return name; } set { name = value; } }
}

Note also; if the xml attributes were just illustrative, then there is a second way to add attributes for things related to data-binding, by using TypeDescriptor.CreateProperty and either ICustomTypeDescriptor or TypeDescriptionProvider. Much more complex than the xml case, I'm afraid - and doesn't work for all code - just code that uses the component-model.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...