Can a custom attribute use other attributes without inheritance?

I am writing some library code, and classes that use this code must have two attributes (one custom attribute and one from .NET).

It is a bit of a hassle to document this requirement and copy and paste both of these attributes into each class that uses my library, so I thought it was better to have my custom attribute, just implying the presence of another.This other attribute from the .NET framework is sealed, although so i cant just inherit it ...

So is there a way to do this? Can I add a .NET attribute at runtime?

Thanks.

+4
source share
2 answers

While you can use inheritance in attributes, it is recommended that you not .

Since this is only a performance rule, you will not violate the correctness, but it can be a source of some confusion, and you should make a lot of effort so as not to violate the semantics of the base attribute. You can cause problems if you try to expand the possible locations for an attribute using the AttributeUsage flags. The rules for the attribute in question are quite complex .

A method can have one of two applied attributes, but not both. Any operation that does not apply uses an attribute that applies to the contained class. If the class containing the class does not have an attribute, the DataContractSerializer is used.

Let it make sealed sounds as a reasonable plan on their part. This API is not designed with these kinds of extensions in mind.

There is no way to add attributes to existing classes at runtime (except for entering AOP code).

+1
source

I do not believe that there is a way to imply secondary attributes or add attributes at runtime. However, you can use a custom code template to add attributes to each class as you add them. And / or for classes that are already developed, I suspect that you can write a macro that goes through each file and add attributes to the classes, however I have not done this before, so I'm not sure if this will entail, I I know that creating a code template to add attributes to a class declaration is relatively simple. But this only works for the class that you add from the point you add the template. If you need to do the cleanup for the old classes as well, I would look at the macros if you have a lot of files / classes, for which it needs to be done. Or do it manually if there aren't many.

0
source

All Articles