jeudi 16 mai 2019

Troubleshoot Parameter Count Mismatch exception when calling PropertyInfo.GetValue

I was wondering if anyone can point me in the right direction.

This the code which is causing parameter count mismatch error.
Parameter Count Mismatch exception when calling PropertyInfo.GetValue. I cannot make it happen on our environments. It happens for one customers production envrionment out of the 5 customers we have that use this code.

 private string getValueFromType(object obj, string type, Type targetClassType, Type currentClassType = null)
        {
            //Reflection to find value for Jack Henry type mapped to specific OnBase KeywordType 
            if (obj == null)
            {
                return String.Empty;
            }
            var objType = obj.GetType();
            if (objType == targetClassType)
            {
                currentClassType = objType;
            }
            var properties = objType.GetProperties();
            var value = String.Empty;
            foreach (var property in properties)
            {
                var propValue = property.GetValue(obj, null);

                var elems = propValue as IList;
                if (elems != null)
                {
                    foreach (var item in elems)
                    {
                        value = this.getValueFromType(item, type, targetClassType, currentClassType);
                        if (value != String.Empty)
                        {
                            return value;
                        }
                    }
                }
                else
                {
                    if (property.PropertyType.Assembly.FullName.StartsWith("JackHenry"))
                    {
                        value = this.getValueFromType(propValue, type, targetClassType, currentClassType);
                        if (value != String.Empty)
                        {
                            return value;
                        }
                    }
                    else
                    {
                        if (currentClassType == targetClassType && objType.FullName == type && property.Name == "Value")
                        {
                            return propValue.ToString();
                        }
                    }
                }
            }
            return value;
        }

I have researched it and some posts said it is because of the object type has an indexed property and you are passing null to the index parameter on the GetValue call. So the solution was to

  var properties = objType.GetProperties().Where(p => p.GetIndexParameters().Length == 0);

But I would like understand why the existing code without indexedparameters line works whenever it does. Any thoughts?





Aucun commentaire:

Enregistrer un commentaire