restricting the property type of a custom attribute
Does anyone knows if it is possible to define/declare on your own custom attribute a restriction to the field type it开发者_StackOverflow中文版 may apply on? There are a flags that do restrict the usage of the attribute:
[AttributeUsage(
AttributeTargets.Property,
AllowMultiple = false)]
Im looking for something like:
UseOnlyOnType = typeof(string)
Any ideas?
This is not possible directly.
But since you have to write code to make use of the attribute (on their own they are just unused metadata), that code could work by only checking for your attribute when the field's type is string
.
There is no way to have the compiler check this for you - your best option will be a execution-time check of the field with reflection.
精彩评论