Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
799 views
in Technique[技术] by (71.8m points)

.net - Parameter Count Mismatch exception when calling PropertyInfo.GetValue

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

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

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?

Solution

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...