C#:如何在运行时向对象添加属性?

C#: How to add an attributes to an object at run-time?(C#:如何在运行时向对象添加属性?)

本文介绍了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#:如何在运行时向对象添加属性?

基础教程推荐