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

use*_*145 11 .net c# attributes

作为一个实体类,我想在运行时添加一个属性,我该怎么办?

Mar*_*ell 11

需要看什么属性?如果它是数据绑定等,TypeDescriptor应该工作:

TypeDescriptor.AddAttributes(type, attribs);
TypeDescriptor.AddAttributes(instance, attribs);
Run Code Online (Sandbox Code Playgroud)

这只会影响System.ComponentModel使用(不是直接反射),但这通常就足够了 - 例如,您可以TypeConverter通过上面的方式关联.

如果"属性"你的意思是"属性",那么(同样,就数据绑定而言)TypeDescriptor也有潜力 - 但它是非平凡的; 你需要ICustomTypeDescriptor在对象上实现,或者CustomTypeDescriptor为类型编写一个- 在任何一种情况下,你需要编写自己的PropertyDescriptor实现(通常与每个实例字典交谈等).这将被使用的任何东西使用:

// only works if you use TypeDescriptionProvider
PropertyDescriptorCollection typeProps = TypeDescriptor.GetProperties(type);
// works via TypeDescriptionProvider or ICustomTypeDescriptor
PropertyDescriptorCollection objProps = TypeDescriptor.GetProperties(obj);
Run Code Online (Sandbox Code Playgroud)

同样,这涵盖了广泛的数据绑定和类似场景.举一个例子,请看这里 - 然而,这远非微不足道.示例用法(来自链接)在运行时添加两个属性:

Bag.AddProperty<int>("TestProp", new DefaultValueAttribute(5)); 
Bag.AddProperty<string>("Name"); 
Run Code Online (Sandbox Code Playgroud)


Rex*_*x M 2

编辑:请澄清一下,您是在谈论类中的C# 属性还是成员?

添加 C# 属性的唯一方法是生成具有附加属性的全新类,编译新程序集并将其加载到现有的 AppDomain。