我想递归构建一个复杂的对象。递归创建自定义复合对象
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;}
}
让我们说,客户生活在一个大会,我加载在飞行:) 我想实例化一个Customer类型的,填充它的属性。 Customer对象具有更多自定义对象和Guid属性。我如何使用递归来创建Customer对象及其嵌套对象。我在下面有一些代码,我偶然发现我应该使用递归。
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;
}
是否有任何的类都有一个构造函数,需要在参数? – dustinmoris 2015-03-02 16:51:36
没有任何类都没有构造函数,在foreach循环中返回的参数 – Mateo 2015-03-02 16:54:42