问题
I want to populate the object's properties with some dummy data. Here is my code but it always returns 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;
}
回答1:
You told it to return null;
, try return obj;
instead.
Also, remove the return
from the if (o != null) return InsertDummyValues(o);
line.
To answer your question in the comment...
else if (property.PropertyType.IsArray)
{
property.SetValue(obj, Array.CreateInstance(type.GetElementType(), 0), null);
}
回答2:
You're missing a return obj;
at the end of the if (obj != null)
block...
来源:https://stackoverflow.com/questions/1539742/filling-out-object-properties-with-default-values-recursive