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

2024-04-30

我想用一些虚拟数据填充对象的属性。这是我的代码,但它总是返回 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;, try return obj;反而。

另外,删除return来自if (o != null) return InsertDummyValues(o); line.

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

else if (property.PropertyType.IsArray)
{
    property.SetValue(obj, Array.CreateInstance(type.GetElementType(), 0), null);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用默认值递归填写对象属性 的相关文章

随机推荐