问题描述
例如,我想删除或更改以下属性属性或添加新属性.有可能吗?
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)
您不能添加实际属性(它们被烧录到 IL 中);但是,使用 XmlSerializer
您不必这样做 - 您可以在构造函数中为 XmlSerializer
提供其他属性.但是,如果这样做,您需要小心地缓存 XmlSerializer
实例,否则它将为每个实例创建一个额外的程序集,这有点泄漏.(如果您使用仅采用 Type
的简单构造函数,则不会这样做).查看 XmlAttributeOverrides
.
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
.
举个例子:
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; } }
}
请注意;如果 xml 属性只是说明性的,那么有一种 second 方法可以为与数据绑定相关的事物添加属性,方法是使用 TypeDescriptor.CreateProperty
和 ICustomTypeDescriptor
或 TypeDescriptionProvider
.恐怕比 xml 的情况复杂得多 - 并且不适用于所有代码 - 只是使用组件模型的代码.
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.
这篇关于我可以在运行时向对象属性添加属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!