jeudi 29 décembre 2016

Object does not match target type when constructing an object dynamically

I have some reflection code that takes one object type and then dynamically creates another object with the same properties (different type) and then sets the properties on the new object.

As seen on the screenshot, the properties are Int32, so I dont know why I am getting this exception on the Setvalue method

Code:

private static T AssembleObject(K sourceObject, T editObject, bool enableAssembleChildObjects, int? level, int? currentLevel)
{
    if (sourceObject == null)
        return default(T);

    T resultObject = (editObject != null) ? editObject : default(T);

    //Se incrementa el nivel de profundidad
    if (currentLevel.HasValue)
        ++currentLevel;

    PropertyInfo[] sourceObjectProperties = typeof(K).GetProperties();
    PropertyInfo[] resultObjectProperties = typeof(T).GetProperties();

    if (sourceObjectProperties != null && resultObjectProperties != null)
    {
        if (editObject == null)
        {
            resultObject = new T();
        }

        for (int i = 0; i < sourceObjectProperties.Length; i++)
        {
            PropertyInfo fromProperty = (PropertyInfo)sourceObjectProperties[i];

            for (int j = 0; j < resultObjectProperties.Length; j++)
            {
                PropertyInfo toProperty = (PropertyInfo)resultObjectProperties[j];

                if (fromProperty.Name == toProperty.Name)
                {
                    //Se obtienen los tipos básicos del objeto
                    if (fromProperty.PropertyType.IsValueType ||
                        (fromProperty.PropertyType.IsArray && fromProperty.PropertyType.GetElementType().IsValueType) ||
                        fromProperty.PropertyType == typeof(System.String))
                    {
                        //Se establece el valor de la propiedad
                        if (toProperty.CanWrite)
                        {

                            toProperty.SetValue(resultObject, fromProperty.GetValue(sourceObject, null), null);
                        }
                    }
                    else
                    {
                        if (enableAssembleChildObjects)
                        {
                            //Validación del nivel de profundidad
                            if (level.HasValue && currentLevel.HasValue && (currentLevel > level))
                                continue;

                            //Se obtiene el tipo del ensamblador
                            Type hermesAssemblerType = typeof(HermesAssembler<,>);
                            //Se definen los argumentos y se crea el tipo genérico dinamicamente
                            Type[] typeArgs = { fromProperty.PropertyType, toProperty.PropertyType };
                            Type resultType = hermesAssemblerType.MakeGenericType(typeArgs);
                            //Se obtiene la lista de métodos del tipo
                            MethodInfo[] methods = resultType.GetMethods(BindingFlags.NonPublic | BindingFlags.Static);
                            string methodName = (fromProperty.PropertyType.IsArray) ? "AssembleObjects" : "AssembleObject";
                            //Se obtiene el método estático específico a ejecutar
                            MethodInfo method = (from m in methods
                                                 where m.Name == methodName && m.GetParameters().Length == 3
                                                 select m).First();
                            //Se obtiene el valor desde la propiedad fuente
                            object sourceValue = fromProperty.GetValue(sourceObject, null);
                            //Se ejecuta el método
                            object resultValue = (sourceValue != null) ? method.Invoke(null, new object[] { sourceValue, level, currentLevel }) : null;

                            if (toProperty.CanWrite)
                            {
                                //Se establece el valor de la propiedad  
                                toProperty.SetValue(resultObject, resultValue, null);
                            }
                        }
                    }

                    break;
                }
            }
        }
    }

    return resultObject;
} 

Screenshot

enter image description here





Aucun commentaire:

Enregistrer un commentaire