问题描述
作为一个实体类,我想补充一个属性在运行时,我应该怎么办?
As an entity class, I want to add a attributes at runtime, 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
的使用(不是直接反映),但往往是不够的 - 例如,你可以关联一个类型转换器
通过上面的。
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);
再次,这涉及面广,数据绑定和类似的情景。对于这样的一个例子,see这里 - 它是远离琐碎,但是。该示例使用(从链接)在运行时增加了两个属性:
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#中:如何添加属性的对象在运行时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!