Reputation: 1359
Heys, guys! I'm trying to get values from my objects by reflection, buy I have a problem: I can get a value from the base object, but I can't get values from inner objects, like this:
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();
}
The base values I can get, but the values of "Person" inner object I can't. Anyone has idea? Thanks!!
Upvotes: 0
Views: 1115
Reputation: 10376
You can update your method like this:
private static void GetDTOProperties(IDictionary<string, object> dicProperties, object objectToSerialize)
{
Type typeOfObject = objectToSerialize is Type ? objectToSerialize as Type : objectToSerialize.GetType();
PropertyInfo[] properties = typeOfObject.GetProperties();
foreach (PropertyInfo property in properties)
{
object val = objectToSerialize is Type ? property.PropertyType : property.GetValue(objectToSerialize, null);
if (!property.PropertyType.IsClass || property.PropertyType.Equals(typeof(string)))
{
dicProperties.Add(string.Format("{0}_{1}", property.DeclaringType.Name.ToLower(), property.Name.ToLower()), val);
}
else
GetDTOProperties(dicProperties, val);
}
}
So there wont ba any problems with objects and you can send actual objects to that method. If you send type of object, than you will get Types as Values in dictionary
Upvotes: 1