我想开始,我不想听到有多昂贵和可怕的反思。这不会有帮助 - 我有充分的理由使用反思,这不是我的问题。
具体来说,我在一个类中有一个类,它包含几个相同类型的静态属性。
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
个对象?
答案 0 :(得分:3)
将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
huzzah减少线条和更多按键......
答案 1 :(得分:2)
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() );
}
}