EDIT:
I’d better rephrase:
How can I shift the GET-implementation of a Class property to a / using a custom attribute? (I’ve added instantation vars (classname, propertyname) to the attribute, however I’d rather have these automatically fetched ofcourse.)
Public Class CustomClass
<CustomAttributeClass(ClassName:="CustomClass", PropertyName = "SomeProperty")> _
Public Property SomeProperty() as String
Get() as String
//This implementation should be handled by the attribute class
End Get
Set(Byval value as String)
Me._someProperty = value
End Set
End Property
End Class
Old question:
I want to create a custom property attribute for classes. I can create a class derived from Attribute, and ‘mark’ the property with the attribute, but where to go from here?
I have a repository where I can quickly get data based on the attributes values. I would like to generalize the behaviour of the property in the attribute but I don’t know how to go from here… Any help would be greatly accepted!
Public Class CustomDataAttribute : Inherits Attribute
Private _name As String
Public Sub New(ByVal name As String)
Me.Name = name
End Sub
Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
Me._name = value
End Set
End Property
End Class
Public Class CustomClass
<CustomDataAttribute(Name:="CustomField")> _
Public Property CustomField()
End Property
End Class
You will have to use Reflection to discover the attribute. In your case, you’ll get it from PropertyInfo.GetCustomAttributes().
The harder part of using attributes is to find a suitable execution model to actually use them. Something like a compiler, a designer or a class that serializes objects is an obvious one. The usability of attributes quickly spirals down from there. It is almost always the wrong choice when you try to use an attribute where a virtual property is actually needed. Retrieving attribute values is very expensive, many orders of magnitude more expensive than retrieving a property value. Use them only when the reflection code runs at human time (like compilers) or when the cost is insignificant compared to the benefit or the overhead (common in any kind of I/O operation).