2016-01-11 44 views
0

我想遍历一个对象并打印所有对象的每个成员的所有值。C#打印一个对象的所有成员的值

我创建下面

public class Employee : Person 
{ 
    public int Salary { get; set; } 
    public int ID { get; set;} 
    public ICollection<ContactInfo> contactInfo { get; set; } 
    public EmployeeValue value { get; set; } 
    public Employee() 
    { 
     contactInfo = new List<ContactInfo>(); 
    } 
} 

public class Person 
{ 
    public string LastName { get; set; } 

    public string FirstName { get; set; } 

    public bool IsMale { get; set; } 
} 

public class ContactInfo 
{ 
    public string email { get; set; } 
    public string phoneNumber { get; set; } 
} 

public class EmployeeValue 
{ 
    public int IQ { get; set; } 

    public int Rating { get; set; } 
} 

测试程序我然后用一些测试数据种子的对象。对象填充后,我尝试遍历所有成员并显示其值。

static void Main(string[] args) 
    { 
     Seed initSeed = new Seed(); 
     object obj = initSeed.getSomebody(); 
     foreach (var p in obj.GetType().GetProperties()) 
     { 

      DisplayProperties(p, obj); 

     }   

     Console.WriteLine("done"); 
     Console.ReadKey(true); 
    } 

static void DisplayProperties(PropertyInfo p, object obj) 
    { 
     Type tColl = typeof(ICollection<>); 

     Type t = p.PropertyType; 
     // If this is a collection of objects 
     if (t.IsGenericType && tColl.IsAssignableFrom(t.GetGenericTypeDefinition()) || 
      t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == tColl)) 
     { 
      System.Collections.IList a = (System.Collections.IList)p.GetValue(obj, null); 
      foreach (var b in a) 
      { 
       foreach(PropertyInfo x in b.GetType().GetProperties()) 
       { 
        DisplayProperties(x, b); 
       } 
      } 

     } 
     // If this is a custom object 
     else if (Convert.ToString(t.Namespace) != "System") 
     { 
      foreach (PropertyInfo nonPrimitive in t.GetProperties()) 
      { 

       DisplayProperties(nonPrimitive, obj); 
      } 
     } 
      // if this is .net framework object 
     else 
     { 
      Console.WriteLine(p.GetValue(obj, null)); 
     } 
    } 

当命名空间是!=“System”,即它是一个自定义对象时,会发生问题。正如这条线所看到的那样; else if (Convert.ToString(t.Namespace) != "System")

功能递归后,它使最终else语句,我得到

“对象不匹配目标类型。”

不知何故,我需要得到一个对象引用的内部对象。

有没有人有任何建议?

+0

为了清楚起见,在Main中播种的obj对象是员工 – user1505192

+0

不,我可能一直不清楚。如果(Convert.ToString(t.Namespace)!=“System”) 则代码将输入 ,那么它将查找嵌套自定义对象的每个属性信息,在这种情况下,它将为EmployeeValue 它会自行递归。递归的下一次迭代将使其到最后的else语句 else Console.WriteLine(p.GetValue(obj,null)); } 此时将会调用一个异常,因为对象obj与目标类型不匹配 – user1505192

回答

1

尝试改变

DisplayProperties(nonPrimitive, obj); 

DisplayProperties(nonPrimitive, p.GetValue(obj, null)); 

然而,这种方法仅当

EmployeeValue value {get;set;} 

不为空。否则它会抛出另一个异常。

+0

现在可行,谢谢 – user1505192

0

您可以简单地覆盖Employee类的toSting()方法。

Overridind toString()

那么员工就会知道如何展示自己。它可以打印在控制台上

Console.WriteLine(employee);