对来自 PropertyInformation 的新类型的泛型方法的递归调用



>我有一个带有子类地址的客户类

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()在属性上设置它

如果你想坚持你目前的方法,那么你需要使用反射从field.PropertyType构建泛型方法调用,如下所述: 反射和泛型类型

但是,您也可以考虑更改方法以接受Type作为参数,而不是创建泛型方法(提示您可以使用Activator.CreateInstance(type)来实例化对象)。

最新更新