C#的回归反射&安培;泛型列表设置默认属性 [英] c# Recursive Reflection & Generic Lists setting default properties
问题描述
我试图使用反射来实现以下目标:
I am trying to to use reflection to achieve the following:
我需要一种方法在那里我传递一个对象,并且此方法将递归实例化子对象对象和设置用默认值的属性。我需要整个对象实例化视需要将尽可能多的水平。
I need a method where i pass in an object and this method will recursively instantiate the object with child objects and set the properties with default values. I need the entire object instantiated going as many levels as needed.
此方法需要能够处理的对象与多个属性,将其它的目的的通用列表。
this method needs to be able to handle an object with a multiple properties that will be generic lists of other objects.
下面是我的示例代码(我得到的参数数量不匹配异常时,我得到包含对象的列表< AnotherSetObjects>
:
Here is my sample code (I am getting a parameter count mismatch exception when i get an object containing a 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);
}
}
}
感谢
Thanks
推荐答案
您可以通过检查 property.PropertyType.IsGeneric
这是通用真正滤除容器。如果需要,还要检查 property.PropertyType.IsArray
。
此外,您还可能希望避免非通用容器。在这种情况下,测试对象为接口类型,例如容器的。例如 - 的IList
You can filter out by checking for property.PropertyType.IsGeneric
which is true for generic containers. If you need, also check for property.PropertyType.IsArray
.
Moreover, you may also want to avoid non-generic containers. In that case, test for object to be of interface types of such containers. Eg - 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#的回归反射&安培;泛型列表设置默认属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!