gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:09:09 32 4
gpt4 key购买 nike

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

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

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

这是我的示例代码(当我得到一个包含 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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com