![](/img/trans.png)
[英]How to I get the parent property's class type after using GetProperties to get a list of properties on a class?
[英]How to get property of a class using GetValue
我有幾個具有屬性的類。 我希望能夠遍歷 class 的屬性並獲取該屬性的值。 我包含了 class 的示例以及我如何循環屬性。 需要幫助了解“GetValue”和“SetValue”的用法
Private Sub loadValues()
Dim mySample As New Sample
Dim props As PropertyInfo() = mySample.GetType().GetProperties()
mySample.Test2 = True
Console.WriteLine(mySample.Test2)
For Each prop In props
Console.WriteLine(prop.Name)
'This will loop through all the properties in the Sample clasee
'How can I get and change the value of each of the properties?
prop.GetValue(mySample, Nothing) '?????
prop.SetValue(mySample, False, Nothing) '?????
Next
End Sub
這是 class 的樣品
Public Class Sample
Public Name As String = "Sample"
Public _Cut As Boolean = False
Private _Test1 As Boolean
Private _Test2 As Boolean
Private _Test3 As Boolean
Public Property Cut(ByVal CabType As String) As Boolean
Get
Return _Cut
End Get
Set(ByVal value As Boolean)
_Cut = value
End Set
End Property
Public Property Test1() As Boolean
Get
Return _Test1
End Get
Set(ByVal value As Boolean)
_Test1 = value
End Set
End Property
Public Property Test2() As Boolean
Get
Return _Test2
End Get
Set(ByVal value As Boolean)
_Test2 = value
End Set
End Property
Public Property Test3() As Boolean
Get
Return _Test3
End Get
Set(ByVal value As Boolean)
_Test3 = value
End Set
End Property
End Class
Cut
屬性已編入索引,因此您需要將一些索引值傳遞給PropertyInfo.GetValue
。 您可能會看到GetValue
的簽名是
Public Overridable Function GetValue(obj As Object, index() As Object) As Object
所以索引參數在索引時需要是一個數組。 在這種情況下,只需將您的Nothing
作為單個元素索引{Nothing}
傳遞。 您可以通過檢查PropertyInfo.GetIndexParameters()
是否有任何東西來判斷是否有索引參數
Private Sub loadValues()
Dim mySample As New Sample
Dim props As PropertyInfo() = mySample.GetType().GetProperties()
mySample.Test2 = True
Console.WriteLine(mySample.Test2)
For Each prop In props
Console.WriteLine(prop.Name)
If prop.GetIndexParameters().Any() Then
prop.GetValue(mySample, {Nothing})
prop.SetValue(mySample, False, {Nothing})
Else
prop.GetValue(mySample, Nothing)
prop.SetValue(mySample, False, Nothing)
End If
Next
End Sub
但是,當您需要傳遞特定索引以正確訪問該屬性時,擁有一個索引屬性然后任意迭代所有屬性可能沒有意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.