Recursive call of generic method with new type from PropertyInfo?

I have a client class with a subclass address

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

I have a method to populate this object with data from xml. Now I want to call this method recursive when it comes a subclass Addressinformation. How can I call my general method with information from 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);
                }
            }
        }
    }
}

I used the best answer with some modification:

Type typeArguments = GetType(field.PropertyType.Namespace + "." + field.PropertyType.Name);
object value = typeof(Helper).GetMethod("ConvertXmlToClass").MakeGenericMethod(typeArguments).Invoke(null, new object[] {xmlDocumentObjectDef, xmlNode, defRelationAttribute});
+3
source share
2 answers

It seems you have a function that converts type names to types, something like this:

Type GetType(string typeName)
{
    return Type.GetType(typeName);
}

then you can call this method as:

object value = typeof(owningType).GetMethod("ConvertXmlToClass").MakeGenericMethod(GetType(typeName)).Invoke(xmlDocumentObjectDef, xmlNode, xmlToClass);

and use PropertyInfo.SetValue()to set it in a property

+2
source

, field.PropertyType, :

Type as (, Activator.CreateInstance(type) ).

+1

All Articles