我尝试使用反射来实现以下目标:C#回归反射和泛型列表设置默认属性
我需要一种方法在那里我传递一个对象,并且此方法将递归实例与子对象的对象,使用默认值设置属性。我需要根据需要将整个对象实例化为多个级别。
此方法需要能够处理具有多个属性的对象,这些属性将成为其他对象的通用列表。
这里是我的示例代码(我收到的参数数量不匹配异常,当我得到含有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);
}
}
}
感谢
这将有助于了解哪条线路出现错误。另外,它看起来像只为类型名称包含BusinessObjects的属性创建新对象,但不清楚这是否是您的意图。 – 2010-04-15 14:45:50