2016-05-20 225 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 - 已經夠難讀了。