c# - 递归创建自定义复杂对象

标签 c# .net generics recursion reflection

我想递归地构建一个复杂的对象。

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

最佳答案

void Main()
{
    Create<Customer>().Dump();
}

// Define other methods and classes here

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

public static T Create<T>()
{
    var type = typeof(T);

    return (T)Create(type);
}

public static object Create(Type type)
{
    var obj = Activator.CreateInstance(type);

    foreach(var property in type.GetProperties())
    {
        var propertyType = property.PropertyType;

        if (propertyType.IsClass 
            && string.IsNullOrEmpty(propertyType.Namespace)
            || (!propertyType.Namespace.Equals("System") 
                && !propertyType.Namespace.StartsWith("System.")))
        {
            var child = Create(propertyType);

            property.SetValue(obj, child);
        }
    }

    return obj;
}

关于c# - 递归创建自定义复杂对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28814954/

相关文章:

c# - 如何调试 Elmah 未在主机上而是在本地记录错误的情况?

c# - 如何正确地将我的 ContextMenu 命令绑定(bind)到 RelayCommand?

c# - 如何在通过 Visual Studio 发布的 C# 程序中包含未编译的内容

c# - 解析 HTML 获取键和值

java - 创建给定类的实例

C++ 通用表数据结构

c# - C#中的using语句和指令有什么区别?

c# - 如何创建带有嵌入图像的 HTML 电子邮件并使用 .net (c#) 在默认邮件客户端中显示它?

php - 如何获取网站的子目录和文件名

java - Android 支持注释 - 如何将 IntDef/StringDef(Typedef 注释)与泛型列表一起使用?