我有一个带有子类地址的客户类
internal class Customer
{
public int id { get; set; }
public string name { get; set; }
[ObjectDefRelation(isSubClass = true)]
public Addressinformation Addressinformation { get; set; }
}
internal class Addressinformation
{
public string street { get; set; }
}
我有一个方法可以用 xml 中的数据填充这个对象。现在我想在它到达子类 Addressinformation
时递归调用此方法。如何使用来自 PropertyInfo
的信息调用我的通用方法?
public static T ConvertXmlToClass<T>(XmlDocument xmlDocumentObjectDef, XmlNode xmlNode, ObjectDefRelationAttribute parentClass = null) where T : new()
{
ObjectDefRelationAttribute defRelationAttribute;
T xmlToClass = new T();
foreach (PropertyInfo field in xmlToClass.GetType().GetProperties())
{
foreach (Attribute attr in field.GetCustomAttributes(true))
{
defRelationAttribute = attr as ObjectDefRelationAttribute;
if (null != defRelationAttribute)
{
if (defRelationAttribute.isSubClass)
{
//
// here I need help to call the recursive method (XXX)
//
var subClass = Helper.ConvertXmlToClass<XXX>(xmlDocumentObjectDef, xmlNode, defRelationAttribute);
}
}
}
}
}
我使用了经过一些修改的最佳答案:
Type typeArguments = GetType(field.PropertyType.Namespace + "." + field.PropertyType.Name);
object value = typeof(Helper).GetMethod("ConvertXmlToClass").MakeGenericMethod(typeArguments).Invoke(null, new object[] {xmlDocumentObjectDef, xmlNode, defRelationAttribute});
最佳答案
看起来你有一个将类型名称转换为类型的函数,就像这样:
Type GetType(string typeName)
{
return Type.GetType(typeName);
}
然后你可以这样调用这个方法:
object value = typeof(owningType).GetMethod("ConvertXmlToClass").MakeGenericMethod(GetType(typeName)).Invoke(xmlDocumentObjectDef, xmlNode, xmlToClass);
并使用 PropertyInfo.SetValue()
在属性上设置它
关于c# - 使用 PropertyInfo 中的新类型递归调用泛型方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6015160/