TypeDescriptor.AddAttributes () replaces the current attribute in addition to adding it

I have this piece of code:

var hasAttribute = TypeDescriptor.GetAttributes(property.DeclaringType).OfType<CrmTypeAttribute>() .Any((attr) => ((CrmTypeAttribute)attr).Name == property.Name); if (!hasAttribute) { var crmTypeAttribute = new CrmTypeAttribute(property.Name, crmType); TypeDescriptor.AddAttributes(property.DeclaringType, crmTypeAttribute); } 

It has two problems:

  • For some reason, OfType returns an empty IEnumerable, although it should return the correct attributes of this type, and I checked. They exist.
  • This is a serious problem. Instead of adding an attribute, it replaces an old attribute of the same type with crmTypeAttribute. I set AllowMultiple to true.

Can someone tell me what is wrong with this code? EDIT:
For some reason, it allows you to add only one attribute type attribute, I added another attribute type at runtime and worked.

+1
source share
2 answers

It turns out that the attribute must override the TypeId property of the Attribute class so that it cannot be duplicated.
For more details see here , it is very hidden and must be specified in GetAttributes.

0
source

I think your problem is that you are ignoring the returned TypeDescriptionProvider from the AddAttributes call.

From reflector to TypeDescriptor.AddAttributes :

Adds class level attributes to the type of the target component.

Options

type : Type target component.

attributes : an array of Attribute objects to add to the component class.

Return value : newly created TypeDescriptionProvider , which was used to add the specified attributes.

When this static method is called, a new instance of TypeDescriptionProvider is always created. You must rely on this newly created provider instance to add additional attributes, as well as requests for newly added attributes.

+1
source

Source: https://habr.com/ru/post/947774/


All Articles