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