C# 用默认值填充对象属性
我想用一些虚拟数据填充对象的属性。这是我的代码,但它总是返回nullC# 用默认值填充对象属性,c#,reflection,properties,objectinstantiation,C#,Reflection,Properties,Objectinstantiation,我想用一些虚拟数据填充对象的属性。这是我的代码,但它总是返回null private static object InsertDummyValues(object obj) { if (obj != null) { var properties = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public);
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;
}
您缺少一个
返回对象在的末尾,如果(obj!=null)
块…您告诉它返回null
,尝试返回obj代码>取而代之
另外,如果(o!=null)返回InsertDummyValues(o),则从中删除返回值
代码>行
要在评论中回答您的问题
else if (property.PropertyType.IsArray)
{
property.SetValue(obj, Array.CreateInstance(type.GetElementType(), 0), null);
}
我添加了它,但它应该返回传递的原始对象,并填充了所有属性。有些属性是有自己属性的类。谢谢!我去掉上面的东西。我现在遇到的一个问题是,在原始对象中存在某个类的集合(数组)。Activator.CreateInstance无法创建数组的对象。谢谢!我去掉上面的东西。我现在遇到的一个问题是,在原始对象中存在某个类的集合(数组)。Activator.CreateInstance无法创建数组的对象。我找到了array.CreateInstance,但大小为。目前还不知道尺寸!Array.CreateInstance不起作用,因为它已经是一个数组。我在回答中添加了,如果它是虚拟数据,只需将其设置为零元素数组,或者如果数组已经初始化,您也可以构建这些数组,然后跳过它,或者您可以使用反射来获取数组的长度。