C#: How to add an attributes to an object at run-time?(C#:如何在运行时向对象添加属性?)
问题描述
作为一个实体类,我想在运行时添加一个属性,应该怎么做?
As an entity class, I want to add an attributes at run-time, how should I do?
推荐答案
需要看什么属性?如果是数据绑定等,TypeDescriptor
应该可以工作:
What needs to see the attributes? If it is things like data-binding etc, TypeDescriptor
should work:
TypeDescriptor.AddAttributes(type, attribs);
TypeDescriptor.AddAttributes(instance, attribs);
这只会影响 System.ComponentModel
的使用(不是直接反射),但这通常就足够了 - 例如,您可以通过上述关联一个 TypeConverter
.
This only affects System.ComponentModel
usage (not direct reflection), but that is often enough - for example, you can associate a TypeConverter
via the above.
如果您所说的属性"是指属性",那么(再次,就数据绑定而言)TypeDescriptor
也有潜力 - 但它并不重要;您需要在对象上实现 ICustomTypeDescriptor
,或者为该类型编写 CustomTypeDescriptor
- 无论哪种情况,您都需要编写自己的 PropertyDescriptor代码> 实现(通常与每个实例的字典等对话).这将被任何使用的东西使用:
If by "attributes" you mean "properties", then (again, as far as data-binding is concerned) TypeDescriptor
also has potential there - but it is non-trivial; you need to either implement ICustomTypeDescriptor
on the object, or to write a CustomTypeDescriptor
for the type - and in either case, you need to write your own PropertyDescriptor
implementation (often talking to a per-instance dictionary etc). This will get used by anything that uses:
// only works if you use TypeDescriptionProvider
PropertyDescriptorCollection typeProps = TypeDescriptor.GetProperties(type);
// works via TypeDescriptionProvider or ICustomTypeDescriptor
PropertyDescriptorCollection objProps = TypeDescriptor.GetProperties(obj);
同样,这涵盖了广泛的数据绑定和类似场景.例如,见这里 -然而,这远非微不足道.示例用法(来自链接)在运行时添加了两个属性:
Again, this covers a wide range of data-binding and similar scenarios. For an example of this, see here - it is far from trivial, however. The example usage (from the link) adds two properties at runtime:
Bag.AddProperty<int>("TestProp", new DefaultValueAttribute(5));
Bag.AddProperty<string>("Name");
这篇关于C#:如何在运行时向对象添加属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C#:如何在运行时向对象添加属性?


- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 使用 rss + c# 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01