2016-11-11 54 views
0

我想将对象转换为ExpandoObject。C#获取属性和子字段的属性递归

到目前为止,我有两个属性和字段的阵列,

Type type = data.GetType(); 
FieldInfo[] fields = type.GetFields(); 
PropertyInfo[] props = type.GetProperties(); 

我可以轻松地步行通过道具,让每个人的价值,并添加到我的ExpandoObject:

public static ExpandoObject ConvertToExpandoObject(object data) 
{ 
    var dynObj = new ExpandoObject(); 

    Type type = data.GetType(); 
    FieldInfo[] fields = type.GetFields(); 
    PropertyInfo[] props = type.GetProperties(); 

    // first the properties... 
    foreach (var property in props) 
    { 
     // add this property 
     ((IDictionary<string, object>)dynObj).Add(property.Name, property.GetValue(data,null)); 

    } 
} 

但然后为每个字段我想再次这样调用转换方法:

foreach (var field in fields) 
{ 
    // add this field 
    ((IDictionary<string, object>)dynObj).Add(field.Name,ConvertToExpandoObject(field?? as an object));    
} 

由于我不知道字段的类型,虽然它是在field.FieldType中,我该如何将字段转换为它自己类型的对象以传递到convert函数?

编辑:

全文作为一个块到希望更清楚:

public static ExpandoObject ConvertToExpandoObject(object data) 
{ 
    var dynObj = new ExpandoObject(); 

    Type type = data.GetType(); 
    FieldInfo[] fields = type.GetFields(); 
    PropertyInfo[] props = type.GetProperties(); 

    // first the properties... 
    foreach (var property in props) 
    { 
     // add this property 
     ((IDictionary<string, object>)dynObj).Add(property.Name, property.GetValue(data,null)); 

    } 
    foreach (var field in fields) 
    { 
     // add this field 
     ((IDictionary<string, object>)dynObj).Add(field.Name,ConvertToExpandoObject(field?? as an object));    
    } 
} 

编辑2:

实施例的对象 - 它们是微不足道的。这可能是学术的,现在我可以很容易地预见时,他们就不会......会回到绘图板

class Parent 
{ 
    public string parentVar { get; set; } 
    public Child child { get; set; } 
} 

class Child 
{ 
    public string childvar { get; set; } 
} 
+0

你为什么要到字段的值转换为'ExpandoObject离开物业的价值,因为它们是? – dymanoid

+0

闻起来真的很腥。您要么按原样添加字段值,要么将其扩展到ExpandoObject,则不能同时执行这两个操作。另外还不清楚为什么你会为一个领域而不是一个属性做这件事,这是没有意义的。如果对象不平凡,当您尝试使用返回的ExpandoObject时,我怀疑会遇到很多麻烦。 –

+0

也许我没有正确解释它。我有一个只有属性的对象,并将它转换为ExpandoObject - 一切都很好。然后,在事物过程中,我有另一个不仅具有属性的对象,而且还有子对象(字段?),每个对象都需要转换为ExpandoObject并作为输出的子项添加ExpandoObject – Morvael

回答

0

我看着它从不同的角度来看, 的最终目的是转化成一个ExpandoObject在序列化之前发送给Web客户端。这是这样的属性可以根据用户的授权被删除..

所以我就连载首先,然后取出属性..

ExpandoObject dynObj = JsonConvert.DeserializeObject<ExpandoObject>(JsonConvert.SerializeObject(data));