使用默认值填充对象属性递归

时间:2009-10-08 18:50:23

标签: 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);

        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; 
}

2 个答案:

答案 0 :(得分:3)

您告诉return null;,请尝试return obj;

另外,从return行中删除if (o != null) return InsertDummyValues(o);

在评论中回答你的问题...

else if (property.PropertyType.IsArray)
{
    property.SetValue(obj, Array.CreateInstance(type.GetElementType(), 0), null);
}

答案 1 :(得分:1)

您在return obj;区块结束时遗漏了if (obj != null) ...

相关问题