嘿,伙计们!我试图通过反射从我的对象中获取值,购买我有一个问题:我可以从基础对象中获取值,但我无法从内部对象中获取值,如下所示:
public class Employee
{
public long EmployeeID { get; set; }
public string EmployeeNumber { get; set; }
public DateTime EmployeeAdmissionDate { get; set; }
public Person EmployeePerson { get; set; }
}
public class Person
{
public long PersonID { get; set; }
public string PersonName { get; set; }
public DateTime PersonBirthday { get; set; }
}
private static void GetDTOProperties(IDictionary<string, object> dicProperties, Type objectToSerialize)
{
Type typeOfObject = objectToSerialize is Type ? objectToSerialize as Type : objectToSerialize.GetType();
PropertyInfo[] properties = typeOfObject.GetProperties();
foreach (PropertyInfo property in properties)
{
if (!property.PropertyType.IsClass || property.PropertyType.Equals(typeof(string)))
dicProperties.Add(string.Format("{0}_{1}", property.DeclaringType.Name.ToLower(), property.Name.ToLower()), property.GetValue(typeOfObject, null));
else
GetDTOProperties(dicProperties, property.PropertyType);
}
}
public static void Main(string[] args)
{
Employee objEmployee = new Employee();
objEmployee.EmployeeID = 1;
objEmployee.EmployeeNumber = 457435;
objEmployee.EmployeeAdmissionDate = DateTime.Now;
objEmployee.EmployeePerson = new EmployeePerson();
objEmployee.EmployeePerson.PersonID = 123;
objEmployee.EmployeePerson.PersonName = "Kiwanax";
objEmployee.EmployeePerson.PersonBirthday = DateTime.Now;
IDictionary<string, object> dicProperties= new Dictionary<string, object>();
GetDTOProperties(dicPropriedades, objEntidadeAluno.GetType());
foreach (string m in dicProperties.Keys)
Console.WriteLine(m + " - " + dicProperties[m]);
Console.ReadLine();
}
我可以获得基本值,但我无法获得“人”内部对象的值。有人有想法吗?谢谢!!