我正在尝试遍历一个对象并打印所述对象的每个成员的所有值。
我在
下面创建了一个测试程序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")
在函数recurses并使其进入最后的else语句后,我得到了
“对象与目标类型不匹配。”
不知何故,我需要获得一个对象引用内部对象。
有人有任何建议吗?
答案 0 :(得分:1)
尝试更改
DisplayProperties(nonPrimitive, obj);
到
DisplayProperties(nonPrimitive, p.GetValue(obj, null));
但是,只有在
时才会有效EmployeeValue value {get;set;}
不为空。否则它会抛出另一个异常。
答案 1 :(得分:0)
您可以简单地覆盖Employee类的toSting()方法。
然后,员工将知道如何展示自己。它可以在控制台上打印
Console.WriteLine(employee);