Why does it return null when I try to invoke gener

2019-07-26 14:11发布

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

2条回答
手持菜刀,她持情操
2楼-- · 2019-07-26 14:44

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

查看更多
啃猪蹄的小仙女
3楼-- · 2019-07-26 14:50
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.

查看更多
登录 后发表回答