1

I've been trying to execute generic methods and using recursion. The problem is that the method GetMethod returns null. How can I improve the code?

public static T GetElementObject<T>(this XElement element)
{
    T returnObject = Activator.CreateInstance<T>();
    PropertyInfo[] propertyInfos = returnObject.GetType().GetProperties();
    Type propertyType;

    foreach (PropertyInfo propertyInfo in propertyInfos)
    {
        propertyType = propertyInfo.PropertyType;

        if (propertyType.IsAssignableFrom(typeof(BaseProxyEntity)))
        {
            MethodInfo getElementObject = typeof(Utility).GetMethod("GetElementObject<>", System.Reflection.BindingFlags.Static | BindingFlags.Public).MakeGenericMethod(propertyType);
            propertyInfo.SetValue(returnObject, getElementObject.Invoke(null, new object[] { element.Descendants(propertyInfo.Name) }), null);
        }
        else if (propertyType.IsValueType == true)
        {
            MethodInfo CastValue = typeof(Utility).GetMethod("CastValue<>", System.Reflection.BindingFlags.Static | BindingFlags.Public).MakeGenericMethod(propertyType);
            propertyInfo.SetValue(returnObject, CastValue.Invoke(null, new object[] { element.Attribute(propertyInfo.Name).Value }), null);
        }
        //Other else conditions ...
    }

    return returnObject;
}
Matthew Strawbridge
  • 19,940
  • 10
  • 72
  • 93
wasimbhalli
  • 5,122
  • 8
  • 45
  • 63
  • Possibly helpful link : http://msdn.microsoft.com/en-us/library/ms172334.aspx – Mikeb Dec 29 '11 at 14:03
  • Are your binding flags correct? Could you show the code for the Utility class? – Wouter de Kort Dec 29 '11 at 14:04
  • There's nothing special in Utility class. It just has some static methods like the one shown above. You can see the method definition for "GetElementObject" which is called recursively. – wasimbhalli Dec 29 '11 at 14:19
  • possible duplicate: http://stackoverflow.com/questions/4035719/getmethod-for-generic-method – phoog Dec 29 '11 at 14:46

2 Answers2

1
GetMethod("GetElementObject<>", ...)

Will allways return null, as there is no such method. Names are mangled for generic types, start with listing all methods and proceed from there.

Eugen Rieck
  • 64,175
  • 10
  • 70
  • 92
1

While Eugen Rieck is correct that names are mangled for generic types, they are not mangled for generic methods. Try without the angle brackets: GetMethod("GetElementObject", ... and GetMethod("CastValue",

phoog
  • 42,068
  • 6
  • 79
  • 117