I'm trying to determine if a interface is decorated with a specific attribute. For example, I have the following interface:
<MyCustomAttribute()> _
Public Interface IMyInterface
Function Function1
Sub DeleteWorkflowInstanceMap(ByVal instanceId As Guid)
Sub InsertWorkflowInstanceMap(ByVal instanceId As Guid, ByVal aliasName As String)
End Interface
How do I determine if IMyInterface is decorated with the MyCustomAttribute attribute?
The same you would normally check for an attribute on a class. Here's some sample code. typeof(ScheduleController) . IsDefined(typeof(SubControllerActionToViewDataAttribute), false);
Attribute ReflectionReflection is a set of . NET APIs that facilitate retrieving metadata from C# attributes. Reflection is used to retrieve attributes associated with an attribute target. This code calls GetCustomAttributes to list the attribute type names for the Id property.
Even better than GetCustomAttributes
is the Shared method IsDefined
:
Attribute.IsDefined(GetType(IMyInterface), GetType(MyCustomAttribute))
GetType(IMyInterface).GetCustomAttributes(GetType(MyCustomAttribute), false).Length > 0
(I hope I have the VB syntax right.) Basically get a Type representing IMyInterface, then call GetCustomAttributes on it passing the type of attribute you're interested in. If that returns a non-empty array, the attribute is present.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With