当我尝试调用泛型方法时,为什么它返回null?

时间:2011-12-29 14:00:09

标签: c# generics reflection

我一直在尝试执行泛型方法并使用递归。问题是方法GetMethod返回null。我该如何改进代码?

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 个答案:

答案 0 :(得分:1)

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

将始终返回null,因为没有这样的方法。对于泛型类型,名称会被修改,从列出所有方法开始,然后从那里开始。

答案 1 :(得分:1)

虽然Eugen Rieck对于泛型类型的名称是正确的,但它们并没有因为泛型方法而受损。尝试不使用尖括号:GetMethod("GetElementObject", ...GetMethod("CastValue",

相关问题