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; }
}
推荐答案
(编辑 - 我误读了原来的问题)
(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.
这篇关于我可以在运行时向对象属性添加属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以在运行时向对象属性添加属性吗?
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 使用 rss + c# 2022-01-01