Adding an attribute to an object at runtime does not occur

I am trying to add attributes to a specific object. This object may be int, string, List, or something else.

I'm trying to use

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

but this attribute list is not showing when I do:

object.GetType().GetCustomAttributes(false)

How did it happen?

Yours faithfully,

Gabriel Paulsson

+3
source share
1 answer

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

Instead, you need to save the return value of the AddAttributes method and the request ...

var myObject = { ... }

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

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

(fixed) , ().

+6

All Articles