Is there an attribute to limit the type to which a user attribute can be applied?

I am writing an attribute (this is a ValidatorAttribute) which currently has

[AttributeUsage(AttributeTargets.Property)] 

which restricts the type of construction over which an attribute can be placed. It can be applied to any object that can exist.

I am wondering if there is an attribute that will limit the Type property to which the attribute can apply. I want to limit it to using DateTime properties.

I see a couple of options, but they are not perfect:

  • I can ignore the attribute instance by checking the type inside the attribute, but there is no pointer to the developer that the attribute does nothing
  • I can throw an exception if Type is wrong, but for obvious reasons this is just a bad idea.

Ideally, I get a compile-time error, just as if I were putting this attribute on anything other than a property:

The attribute is not a valid declaration type. This is true only for the 'property, indexer' declaration.

I do not expect that there is such an attribute, but I am happy to be mistaken. Or did someone write such an attribute (is this possible?) Or any suggested alternatives?

+4
source share
2 answers

The only way to ensure this is to write a post-build tool that lists all the types in the assembly and checks if yours were applied to the correct ones. There is not much sense; an attribute simply will not have any effect; if it was applied incorrectly, you simply cannot find it.

+2
source

One tool that could do what @Hans Passant offers is the following: http://www.postsharp.net/ Another option is to use a language like Boo , a .NET compatible language that supports the Abstract syntax manipulation tree as part of the compilation chain . This would allow the creation of a macro that will be executed at compile time to perform appropriate type checking.

0
source

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


All Articles