lundi 2 mars 2015

recursively create custom complex object

I would like to recursively build an complex object.



public class Name
{
public string firstName {get;set;}
public string lastName {get;set;}
}

public class Address
{
public string city {get;set;}
public string state {get;set;}
public string street {get;set;}
public string zip {get;set;}
}

public class Customer
{
public Name customerName {get;set;}
public Address customerAddress {get;set;}
public Guid id {get;set;}
}


Lets say that Customer lives in an assembly that I'm loading on the fly :) I want to instantiate a type of Customer and populate its properties. Customer object has more custom objects and a Guid property. How can I use recursion to create the Customer object and its nested objects. I have some code below where I stumbled into the fact that I should be using recursion.



static object TraversePropertyInfo(object obj, Assembly assembly)
{
Console.WriteLine(obj.GetType().Name);

foreach(PropertyInfo pi in obj.GetType().GetProperties())
{
if(pi.PropertyType.IsClass && pi.PropertyType.Namespace != "System")
{
if(pi.PropertyType.UnderlyingSystemType.GenericTypeArguments.Count() > 0)
{
Console.WriteLine("\tIList<{0}>", pi.Name);
}
else
{
Console.WriteLine("\t{0}\t<class>", pi.Name);
object child = Activator.CreateInstance(assembly.GetType(pi.PropertyType.FullName)); // create the child instance
obj.GetType().GetProperty(pi.Name).SetValue(obj, child); // set the child on the parent
// but the child can have children...
// I should be using recurrsion here
}
}
else
{
Console.WriteLine("\t{0}\t{1}", pi.Name, pi.PropertyType);
}
}
return obj;
}





Aucun commentaire:

Enregistrer un commentaire