调用PropertyInfo.GetValue当参数计数不匹​​配异常异常、参数、PropertyInfo、GetValue

2023-09-03 04:50:53 作者:人来狗往

我想比较使用反射来通过使用下面的方法及其属性回路运行时的两个对象:

I'm trying to compare two objects at runtime using reflection to loop through their properties using the following method:

Private Sub CompareObjects(obj1 As Object, obj2 As Object)

    Dim objType1 As Type = obj1.GetType()

    Dim propertyInfo = objType1.GetProperties

    For Each prop As PropertyInfo In propertyInfo
        If prop.GetValue(obj1).Equals(prop.GetValue(obj2)) Then
            'Log difference here
        End If
    Next
End Sub

每当我测试这个方法,我得到一个参数计数从System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck不匹配异常时,它调用prop.GetValue(OBJ1)。

Whenever I test this method, I'm getting a Parameter Count Mismatch exception from System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck when it calls prop.GetValue(obj1).

这会发生,无论OBJ1和OBJ2的类型,也没有在道具类型(在我的测试情况下,第一属性是一个布尔值)。

This happens no matter the type of obj1 and obj2, nor the type in prop (in my test case, the first property is a Boolean).

我是什么做错了,我怎么能解决这个问题,这样我可以从两个对象比较值?

What am I doing wrong and how can I fix it so that I can compare the values from the two objects?

解决方案

我添加了以下几行只是里面的每个循环:

I added the following lines just inside the for each loop:

Dim paramInfo = prop.GetIndexParameters
If paramInfo.Count > 0 Then Continue For

第一个属性正在采取的一个参数,这是造成问题的原因。现在,我就跳过这需要一个参数的任何属性。

The first property was taking a parameter, which was causing the problem. For now, I'll just skip any property that requires a parameter.

推荐答案

我怀疑你的类型包含一个索引 - 即一个属性,它需要的参数。你可以通过调用PropertyInfo.GetIndexParameters并检查是否返回的数组是空的。

I suspect your type contains an indexer - i.e. a property which takes parameters. You can check for this by calling PropertyInfo.GetIndexParameters and checking if the returned array is empty.

(如果的不是的问题,请编辑您的问题表现出短暂而完整的节目展示了问题。)

(If that isn't the problem, please edit your question to show a short but complete program demonstrating the issue.)