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;
}
可能有用的链接:http://msdn.microsoft.com/en-us/library/ms172334.aspx – Mikeb 2011-12-29 14:03:15
您的绑定标志是否正确?你能显示Utility类的代码吗? – 2011-12-29 14:04:09
Utility类没有什么特别的。它只是有一些像上面所示的静态方法。您可以看到递归调用的“GetElementObject”的方法定义。 – wasimbhalli 2011-12-29 14:19:27