如何使用 GetValue 获取 class 的 属性

How to get property of a class using GetValue

我有几个 class 属性。我希望能够遍历 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

但是,当您需要传递特定索引以正确访问 属性.

时,拥有索引 属性 然后任意遍历所有属性可能没有意义