mardi 24 février 2015

Using Reflection to Get All Static Properties in a Class As Objects VB.NET

I would like to start that I don't want a to hear about how expensive and terrible reflection is. That won't help—I have a very good reason to use reflection and that's not my question.


Specifically, I have a class within a class that contains several static properties of the same type.



Public Class Foo
Public Class Bar
Public Shared Property prop1 As New CustomClass()
Public Shared Property prop2 As New CustomClass()
Public Shared Property prop3 As New CustomClass()
End Class
End Class

Public Class CustomClass
Public Sub DoStuff()
End Sub
End Class


I'm looking to create a method in Foo that calls DoStuff on each of the properties contained within it. How can I do this? Here's the general idea of what I want to include in Foo, but I obviously can't convert PropertyInfo to CustomClass:



Private Sub Example()
For Each prop As PropertyInfo In GetType(Foo.Bar).GetProperties()
DirectCast(prop, CustomClass).DoStuff()
Next
End Sub


How can I get the static properties and cast them to CustomClass objects?






Aucun commentaire:

Enregistrer un commentaire