使用反射获取 Class 作为对象 VB.NET 中的所有静态属性

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

首先我想说的是,我不想听到反射是多么昂贵和可怕。这无济于事——我有充分的理由使用反射,这不是我的问题。

具体来说,我在 class 中有一个 class,其中包含多个相同类型的静态属性。

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

我想在 Foo 中创建一个方法,该方法调用 DoStuff 中包含的每个属性。我怎样才能做到这一点?这是我想在 Foo 中包含的内容的总体思路,但我显然无法将 PropertyInfo 转换为 CustomClass:

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

如何获取静态属性并将它们转换为 CustomClass 个对象?

PropertyInfo 表示类型的 属性 get/set 方法对。要计算 getter,您只需调用 GetValue,如下所示:

(在 C# 中,因为我是一个语言势利小人)

foreach( PropertyInfo pi in typeof(Foo.Bar).GetProperties() ) {

    // Use null as arguments because it's a static property without an indexer.
    Object got = pi.GetValue( null, null ); 
    CustomClass got2 = got as CustomClass;
    if( got2 != null ) {
        Console.WriteLine( got2.ToString() );
    }
}

并将 Dai 的答案转换为 VB,因为我不是语言势利小人:

For Each pi As System.Reflection.PropertyInfo in Foo.Bar.GetType.GetProperties()
    ' Use nothing as arguments because it's a shared property without an indexer.
    Dim got = pi.GetValue(Nothing, Nothing)
    Dim got2 as CustomClass = DirectCast(got, CustomClass)
    If Not IsNothing(got2) Then Console.WriteLine(got2.toString())
Next

为更少的行和更多的击键而欢呼...