2016-05-20 177 views
0

我试图获取对象的所有属性及其值。 这里我的代码给我所有的价值为我对象的“简单”的属性:获取嵌套对象的属性

    foreach (var prop in dataItem.Value.GetType().GetProperties()) 
        { 
         if (prop.Name == "CurrentSample") 
         { 
          //Doesn't work 
          var internProperties = prop.GetType().GetProperties(); 
          foreach (var internProperty in internProperties) 
          { 
           System.Diagnostics.Debug.WriteLine("internProperty.Name + " : " + internProperty.GetValue(prop, null)); 
          } 
         } 
         else 
         { 
          System.Diagnostics.Debug.WriteLine(prop.Name + " : "+ prop.GetValue(dataItem.Value, null)); 
         } 
        } 

我的问题是关于我的“CurrentSample”属性,它包含自己的(时间戳和字符串)的2财产。 我无法找到检索这些信息的方法。

我试图应用相同的原则,但我根本得不到正确的信息。我可以通过使用一个简单的dataItem.Value.CurrentSample.Value或dataItem.Value.CurrentSample.TimeStamp来访问这些值,但想知道一个更正确的方法来使其工作。

现在,而不是打印我的时间戳和值与自己的价值,我得到属性的大名单,我想的类属性的所有属性:

ReflectedType : MTConnectSharp.DataItem 
MetadataToken : 385876007 
Module : MTCSharp.dll 
PropertyType : MTConnectSharp.DataItemSample 
Attributes : None 
CanRead : True 
CanWrite : False 
GetMethod : MTConnectSharp.DataItemSample get_CurrentSample() 
SetMethod : 
IsSpecialName : False 
CustomAttributes : System.Collections.ObjectModel.ReadOnlyCollection`1[System.Reflection.CustomAttributeData] 
+0

这些属性是受保护的/私人的吗? –

+0

不,他们都是公开的。 – Belterius

+0

好的,那么错误是什么?你说这不起作用,但为什么? –

回答

1

我猜你有一个问题,这条线:

var internProperties = prop.GetType().GetProperties(); 

它应该返回PropertyInfo属性,因为您没有首先获取属性值。

有了:

var internProperties = prop.GetValue(dataItem.Value, null).GetType().GetProperties(); 

应该更好地工作。

而对于这一点:

System.Diagnostics.Debug.WriteLine("internProperty.Name + " : " + internProperty.GetValue(prop, null)); 

您仍然希望道具值,而不是物业本身。

+0

现在确实有效,谢谢。 – Belterius

0

这一部分:

internProperty.GetValue(prop, null) 

意味着你想获得的prop一个属性,它是一个PropertyInfo实例的值。相反,您应该使用:

if (prop.Name == "CurrentSample") 
{ 
    object currentSample = prop.GetValue(dataItem.Value, null); 
    var internProperties = prop.GetType().GetProperties(); 
    foreach (var internProperty in internProperties) 
    { 
     System.Diagnostics.Debug.WriteLine("internProperty.Name + " : " + internProperty.GetValue(currentSample , null)); 
    } 
} 

PS。就我个人而言,我尽量避免在任何反射代码中使用var - 已经够难读了。