Why does it return null when I try to invoke gener

2019-07-26 14:24发布

问题:

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;
}

回答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",



回答2:

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.