为什么当我尝试调用泛型方法时返回null? [英] Why does it return null when I try to invoke generic methods?
本文介绍了为什么当我尝试调用泛型方法时返回null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试执行泛型方法并使用递归。问题是方法 GetMethod
返回 null
。
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;
}
推荐答案
Eugen Rieck是正确的名称为通用类型而被修改,但它们不会被泛型方法修改。尝试不使用尖括号: GetMethod(GetElementObject,...
和 GetMethod(CastValue,
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",
这篇关于为什么当我尝试调用泛型方法时返回null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文