我有幾個帶有屬性的類。我希望能夠遍歷類的屬性并獲取該屬性的值。我包括了一個類的示例以及我如何回圈屬性。需要幫助理解“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
這是類的示例
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
uj5u.com熱心網友回復:
該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
但是,當您需要傳遞特定索引以正確訪問屬性時,擁有索引屬性然后任意迭代所有屬性可能沒有意義。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/384929.html
標籤:网络
上一篇:向使用GDI 繪制的影像添加文本
