C#: How to add an attributes to an object at run-time?

后端 未结 7 1966
孤独总比滥情好
孤独总比滥情好 2020-12-30 09:00

As an entity class, I want to add an attributes at run-time, how should I do?

7条回答
  •  没有蜡笔的小新
    2020-12-30 09:26

    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);
    

    This only affects System.ComponentModel usage (not direct reflection), but that is often enough - for example, you can associate a TypeConverter via the above.

    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("TestProp", new DefaultValueAttribute(5)); 
    Bag.AddProperty("Name"); 
    

提交回复
热议问题