开发者

Recursive call on generic method with new type from PropertyInfo?

开发者 https://www.devze.com 2023-03-06 09:12 出处:网络
I have a customer class with a sub-class address internal class Customer { public int id { get; set; } public string name { get; set; }

I have a customer class with a sub-class address

internal class Customer    
{
    public int id { get; set; }
    public string name { get; set; }

    [ObjectD开发者_高级运维efRelation(isSubClass = true)]
    public Addressinformation Addressinformation { get; set; }
}

internal class Addressinformation 
{
    public string street { get; set; }
}

I have a Method to fill this object with data from a xml. Now I want to call this method recursive when its arrive the sub-class Addressinformation. How can I call my generic method with informations 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});


It seems that you've got 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 on the property


If you want to stick with your current approach then you need to use reflection to built the generic method call from the field.PropertyType as described here: Reflection and generic types

However you could also consider changing your method to accept a Type as parameter instead of making a generic method (hint you can use Activator.CreateInstance(type) to instantiate an object).

0

精彩评论

暂无评论...
验证码 换一张
取 消