我可以在运行时将属性添加到一个对象的属性? [英] Can I add attributes to an object property at runtime?
问题描述
例如我想删除或更改以下属性的属性或添加一个新的。这可能吗?
[的XmlElement(bill_info)]
[XmlIgnore]
公共BillInfo BillInfo
{
{返回billInfo; }
集合{billInfo =价值; }
}
(编辑 - 我误解了原来的问题)
您不能添加实际属性(它们烧入IL);然而,随着的XmlSerializer
你没有 - 你可以在构造函数中的的XmlSerializer
提供额外的属性。你这样做,不过,需要小心一点缓存的XmlSerializer
例如,如果你这样做,否则会造成每个实例的附加组件,这是一个有点漏水。 (如果你用简单的构造函数,只需要一个它不会做这种类型的
)。看<一个href=\"http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlattributeoverrides.aspx\"><$c$c>XmlAttributeOverrides$c$c>.
有关的例子:
使用系统;
使用的System.Xml.Serialization;
公共类Person
{
静态无效的主要()
{
XmlAttributeOverrides覆盖=新XmlAttributeOverrides();
XMLATTRIBUTES attribs =新XMLATTRIBUTES();
attribs.XmlIgnore = FALSE;
attribs.XmlElements.Add(新XmlElementAttribute(PERSONNAME));
overrides.Add(typeof运算(人),姓名,attribs); XmlSerializer的SER =新的XmlSerializer(typeof运算(人),覆盖);
人人=新的Person();
person.Name =马克;
ser.Serialize(Console.Out,人);
}
私人字符串名称;
[的XmlElement(名称)]
[XmlIgnore]
公共字符串名称{{返回名称; } {设置名称=值; }}
}
还要注意;如果XML属性只是示意性的,再有一个的第二的方式使用,增加了对有关事情的数据绑定,属性 TypeDescriptor.CreateProperty
,要么 ICustomTypeDescriptor
或 TypeDescriptionProvider
。要复杂得多比XML的情况下,恐怕 - 以及所有code不工作 - 只需$使用该组件模型C $ C
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; }
}
(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.
这篇关于我可以在运行时将属性添加到一个对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!