C#:如何在运行时的属性添加到一个对象? [英] C#: How to add an attributes to an object at run-time?

查看:718
本文介绍了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#:如何在运行时的属性添加到一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆