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

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

最佳答案

你告诉它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/

相关文章:

reflection - kotlin 别名属性委托(delegate)抛出异常

c# - 静态类中的 Thread.Sleep()

c# - MSDTC从独立机器到域机器

c# - 学习有效地使用接口(interface)

reflection - 类方法的 noSuchMethod(又名静态方法)

java - 访问返回类型的泛型参数

c# - 如何使用左侧带有 Type 的 IS 运算符?

c# - SignalR - 无法为 SSL/TLS 安全通道建立信任关系

c# - 查找 Func 委托(delegate)的调用方法的名称

javascript - EmberJS - 将相同的值分配给依赖属性时更新计算属性