简体   繁体   中英

Adding attribute on object during run time not happening

I try to add attributes on a certain object. This object can be int, string, List or whatever.

I try to use

TypeDescriptor.AddAttributes(object, attrList.ToArray());

but this list of attributes do not show up when I do:

object.GetType().GetCustomAttributes(false)

How come?

Best regards,

Gabriel Paulsson

Unfortunately this method does not dynamically change the metadata of the type, ultimately it only gives you back a TypeDescriptor which includes the attributes you added.

You need to keep the return value of the AddAttributes method and query from there instead...

var myObject = { ... }

var typeDescriptionProvider = TypeDescriptor.AddAttributes(myObject, attrList.ToArray());

var attributes = typeDescriptionProvider.GetTypeDescriptor(myObject).GetAttributes();

You can think of the type descriptor as a union of the type metadata itself (fixed), and any meta data you added at runtime (dynamic).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM