使用GetValue和System.Reflection

时间:2016-06-14 13:06:12

标签: vb.net system.reflection

使用VB.Net。我试图从同一个类的两个对象获取属性值并进行比较。如果值不同,那么我想将它们添加到一个字符串中,显示值是什么以及它们改变了什么。我遇到了GetValue的问题。 以下是此功能的代码:

  Public Function GetRowChangesList(ByVal Before As IEnumerable(Of Object), ByVal After As IEnumerable(Of Object), ByRef isNew As Boolean) As String

    Dim TheseChanges As List(Of String) = Nothing

    'any errors, return ""
    Try

        'If Lists are both empty, return
        If Before Is Nothing And After Is Nothing Then
            Return ""
        End If

        'Figure out the object type and make sure before and after match
        Dim DataTypeBefore As Type
        Dim DataTypeAfter As Type

        DataTypeBefore = Before.Single.GetType()
        DataTypeAfter = After.Single.GetType()

        'if they don't match function won't work
        If DataTypeBefore IsNot DataTypeAfter Then
            Return ""
        End If


        Dim myField As PropertyInfo() = Before.Single.GetType().GetProperties()
        Dim myField2 As PropertyInfo() = After.Single.GetType().GetProperties()

        'Find the changes
        Dim index As Integer

        For index = 0 To myField2.Length - 1
            If Not myField(index).GetValue(Before) = myField2(index).GetValue(After) Then

                TheseChanges(0) += ("Change happened at:  " + myField(index).Name.ToString + "  Values changed from: " +
                     myField(index).GetValue(Before).ToString + " To " + myField2(index).GetValue(After).ToString)

            End If
        Next

    Catch ex As Exception

        'send error
        SendErrorEmail(ex, "Saving changes for: '" + Before.Single.GetType().ToString)

    End Try

    'return
    Return TheseChanges(0)

End Function

如果发生任何变化,应该只有一件事情发生了变化。这就是为什么它只返回第一个元素。当我调试时,它每次捕获一个异常。它给我的错误如下:

        If Not myField(index).GetValue(Before) = myField2(index).GetValue(After) Then   error BC30199: '(' expected.    
    TheseChanges(0) = ("Change happened at:  " + myField(index).Name.ToString + "  Values changed from: " + error BC30201: Expression expected. 
    myField(index).GetValue(Before).ToString + " To " + myField2(index).GetValue(After).ToString)   error BC37237: ')' is not a valid format specifier  
    End If  error BC30201: Expression expected. 
    Next    error BC30201: Expression expected. 

编辑: 我只是尝试了这种方法,但仍然遇到了同样的错误(代码如下)。也只是尝试将'='更改为isNot(没有改变任何东西),我也尝试在每个值周围添加parens,这也没有改变任何东西。

If myField(index).GetValue(myField(index).Name) = myField2(index).GetValue(myField(index).Name)

1 个答案:

答案 0 :(得分:1)

变化:

If Not myField(index).GetValue(Before) = myField2(index).GetValue(After) Then

要:

If Not myField(index).GetValue(Before.Single) = myField2(index).GetValue(After.Single) Then

说明:

myField是为类型Before.Single创建的,但您使用的是Before,其类型与Before.Single不同。