.net - 调用PropertyInfo.GetValue时参数计数不匹配异常

标签 .net reflection

我试图在运行时使用反射比较两个对象,以使用以下方法遍历它们的属性:

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

每当我测试此方法时,都会在调用prop.GetValue(obj1)时从System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck获得参数计数不匹配异常。

无论obj1和obj2的类型如何,还是prop中的类型(在我的测试案例中,第一个属性都是 bool(boolean) 值),这种情况都会发生。

我在做什么错,如何解决它,以便可以比较两个对象的值?

解决方案

我在每个循环的内添加了以下几行:
Dim paramInfo = prop.GetIndexParameters
If paramInfo.Count > 0 Then Continue For

第一个属性是一个参数,这导致了问题。现在,我将仅跳过任何需要参数的属性。

最佳答案

我怀疑您的类型包含索引器-即带有参数的属性。您可以通过调用 PropertyInfo.GetIndexParameters 并检查返回的数组是否为空来进行检查。

(如果这不是问题,请编辑您的问题以显示一个简短而完整的程序来演示该问题。)

关于.net - 调用PropertyInfo.GetValue时参数计数不匹配异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18721920/

相关文章:

.net - 如何在 Visual Studio 2013 中为经典 ASP 启用智能感知和语法突出显示

c# - 如何将 lambda 表达式传递给 WCF 服务?

.net - 清除 NavigationService 中的前向条目

c# - 在 .NET .config 文件中读取和写入值

C# 反射 : What is the difference between FieldInfo. SetValue() 和 FieldInfo.SetValueDirect()?

reflection - Kotlin 中 KProperty1 的通用扩展

.net - 有时是否必须使用 COM 对象显式调用 gc.collect

Java动态函数调用

ASP.NET 页面继承

python - 获取函数的源文件行号