2011-12-29 45 views
1

我一直在尝试执行泛型方法并使用递归。问题是方法GetMethod返回null。我如何改进代码?当我尝试调用泛型方法时为什么返回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; 
} 
+0

可能有用的链接:http://msdn.microsoft.com/en-us/library/ms172334.aspx – Mikeb 2011-12-29 14:03:15

+0

您的绑定标志是否正确?你能显示Utility类的代码吗? – 2011-12-29 14:04:09

+0

Utility类没有什么特别的。它只是有一些像上面所示的静态方法。您可以看到递归调用的“GetElementObject”的方法定义。 – wasimbhalli 2011-12-29 14:19:27

回答

1

尽管Eugen Rieck是正确的,名称被修改为泛型类型,但它们不会被泛型化为泛型方法。尝试不带尖括号:GetMethod("GetElementObject", ...GetMethod("CastValue",

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

将永诺返回null,因为没有这样的方法。对于泛型类型,名称会被修改,首先列出所有方法并从那里继续。