c# - 使用 PropertyInfo 中的新类型递归调用泛型方法?

标签 c# reflection recursion

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

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/

相关文章:

java - Android列出所有ftp文件夹和子文件夹

c# - 在不使用不安全的情况下将 int 分配给结构对象

c# - 如何使用 c# 对单个字符串中的多个项目进行正则表达式?

c# - 定义无效异常 : The definition of the report '' is invalid

c# - 如何使用反射获取继承属性的值?

iphone - 我如何从 Objective-C 中的类属性中获取值?

c - 二叉搜索树指针问题

c# - 找不到引用。(您是否缺少 using 指令...)

c# - 显示对象的内容

javascript - 将代码重构为尾递归