我想用一些虚拟数据填充对象的属性。这是我的代码,但它总是返回 null。
private static object InsertDummyValues(object obj)
{
if (obj != null)
{
var properties = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public);
foreach (var property in properties)
{
if (property.PropertyType == typeof (String))
{
property.SetValue(obj, property.Name.ToString(), null);
}
else if (property.PropertyType == typeof(Boolean))
{
property.SetValue(obj, true, null);
}
else if (property.PropertyType == typeof(Decimal))
{
property.SetValue(obj, 23.5, null);
}
else
{
// create the object
var o = Activator.CreateInstance(Type.GetType(property.PropertyType.Name));
property.SetValue(obj,o,null);
if (o != null)
return InsertDummyValues(o);
}
}
}
return obj;
}
最佳答案
你告诉它return null;
,试试return obj;
。
此外,从 if (o != null) return InsertDummyValues(o);
行中删除 return
。
在评论中回答你的问题......
else if (property.PropertyType.IsArray)
{
property.SetValue(obj, Array.CreateInstance(type.GetElementType(), 0), null);
}
关于c# - 使用默认值递归填充对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1539742/