2014-11-03 20 views
1

我想從對象的實例獲取屬性名稱和值。我需要它爲包含嵌套對象的對象工作,我可以簡單地在父實例中傳遞對象。如何使用反射和遞歸獲取任何對象的所有名稱和值

舉例來說,如果我有:

public class ParentObject 
{ 
    public string ParentName { get; set; } 
    public NestedObject Nested { get; set; } 
} 

public class NestedObject 
{ 
    public string NestedName { get; set; } 
} 

// in main 
var parent = new ParentObject(); 
parent.ParentName = "parent"; 
parent.Nested = new NestedObject { NestedName = "nested" };         

PrintProperties(parent); 

我試圖遞歸方法:

public static void PrintProperties(object obj) 
{ 
    var type = obj.GetType(); 

    foreach (PropertyInfo p in type.GetProperties()) 
    { 
     Console.WriteLine(p.Name + ":- " + p.GetValue(obj, null)); 

     if (p.PropertyType.GetProperties().Count() > 0) 
     {    
      // what to pass in to recursive method 
      PrintProperties();          
      } 
     } 

     Console.ReadKey(); 
    } 

如何確定該屬性是什麼,然後在傳遞到PrintProperties?

+1

之前調用「的GetProperties,」你應該檢查的類型(是一類?),以獲得一定的GetProperties是相關的。要獲得值,請分別調用p.GetValue(obj),並使用「p」將其傳遞給「PrintProperty」方法。 – AFract 2014-11-03 10:29:04

回答

2

你得到的價值已經,試試這個:

object propertyValue = p.GetValue(obj, null); 
Console.WriteLine(p.Name + ":- " + propertyValue); 

if (p.PropertyType.GetProperties().Count() > 0) 
{    
    // what to pass in to recursive method 
    PrintProperties(propertyValue); 
} 
+0

謝謝。這是確切的;Ÿ我在那裏失蹤。 – davy 2014-11-03 10:33:35

相關問題