Re: Custom Attributes, Shared methods, Derived classes and reflection



On 31 Jul 2006 07:32:01 -0700, tommaso.gastaldi@xxxxxxxxxxx wrote:


See if this get close to what you want (watch out line breaks, VB
2005):

[snippage]

Dim MyDerivedClass As New MyDerivedClass_Instance

[snippage]

<MyCustomAttribute("Hi", "Jeff")> _
Public Class MyDerivedClass_Instance
Inherits MyBaseClass

End Class

Class MyBaseClass


[snippage]

Public Shared ReadOnly Property S_ValueFromMyAttribute(ByVal
Index As Integer) As String
Get
Dim classtype As Type = GetType(MyDerivedClass)
Dim attr As MyCustomAttribute =
DirectCast(Attribute.GetCustomAttribute(classtype,
GetType(MyCustomAttribute)), MyCustomAttribute)
If attr IsNot Nothing Then
Select Case Index
Case 1
Return attr.PropertyForString1
Case 2
Return attr.PropertyForString2
Case Else
Return "unexpected arg"
End Select
Else
Return "no attribute"
End If
End Get
End Property

End Class

End Class

Ah, but MyBaseClass is used as a base for many different classes, so referring to the
derived class via GetType(MyDerivedClass) won't do, since that "hardwires" a
particular derived class inside the base class. Any number of other classes would
also derive from the base, each with their own attribute.

As I think about it, there could even be an entire class hierarchy which derives from
the base class. It would be a reasonable restriction for the base to assume that the
attribute only appeared on the most derived class from the base.

-- Jeff
.