c# 递归反射和通用列表设置默认属性

标签 c# generics reflection recursion

我正在尝试使用反射来实现以下目标:

我需要一个传入对象的方法,此方法将使用子对象递归实例化该对象并使用默认值设置属性。我需要根据需要将整个对象实例化到尽可能多的级别。

此方法需要能够处理具有多个属性的对象,这些属性将是其他对象的通用列表。

这是我的示例代码(当我得到一个包含 List<AnotherSetObjects> 的对象时,我得到一个参数计数不匹配异常:

private void SetPropertyValues(object obj)
{
    PropertyInfo[] properties = obj.GetType().GetProperties();

    foreach (PropertyInfo property in properties)
    {
        if (property.PropertyType.IsClass && property.PropertyType != typeof(string) && property.PropertyType.FullName.Contains("BusinessObjects"))
        {
            Type propType = property.PropertyType;

            var subObject = Activator.CreateInstance(propType);
            SetPropertyValues(subObject);
            property.SetValue(obj, subObject, null);
        }
        else if (property.PropertyType == typeof(string))
        {
            property.SetValue(obj, property.Name, null);
        }
        else if (property.PropertyType == typeof(DateTime))
        {
            property.SetValue(obj, DateTime.Today, null);
        }
        else if (property.PropertyType == typeof(int))
        {
            property.SetValue(obj, 0, null);
        }
        else if (property.PropertyType == typeof(decimal))
        {
            property.SetValue(obj, 0, null);
        }
    }
}

谢谢

最佳答案

您可以通过检查 property.PropertyType.IsGeneric 来过滤掉,这对于通用容器是正确的。如果需要,还检查 property.PropertyType.IsArray

此外,您可能还想避免使用非通用容器。在这种情况下,测试对象是否属于此类容器的接口(interface)类型。例如 - IList

bool isList(object data)
{
    System.Collections.IList list = data as System.Collections.IList;
    return list != null;
}

...
if (isList(obj)) {
    //do stuff that take special care of object which is a List
    //It will be true for generic type lists too!
}

关于c# 递归反射和通用列表设置默认属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2646224/

相关文章:

c# - 使用 Graph API 在 Azure Active Directory (B2C) 中使用 http post 请求创建新用户

c# - 如何使用 Excel-DNA 创建新工作表并用数据行填充它?

Swift 4——尝试使用泛型来减少公式化代码的挑战

java - Eclipse 中通用类型的自动完成

java - 使用 ASM 获取方法参数

java - 如何查找java bean中包含的所有成员变量的字段

c# - 使用接口(interface)在 C++ 中使用通用容器的最佳方法是什么(即等同于在 C# 中将 IEnumerable 作为参数)

java - Java泛型方法返回类型中的上界和下界通配符

java - 如何检查 Class<?> 对象实例的 "?"是否为 SomeInterface

c# - XML 从 nextNode 获取值