通过反射从类中获取内部对象的值

时间:2012-08-06 11:24:44

标签: c# reflection

嘿,伙计们! 我试图通过反射从我的对象中获取值,购买我有一个问题:我可以从基础对象获取值,但我无法从内部对象获取值,如下所示:

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();
    }

我可以得到的基本值,但“人”内部对象的值我不能。有人有想法吗?谢谢!

1 个答案:

答案 0 :(得分:1)

您可以像这样更新您的方法:

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);
   }
}

因此,对象不会出现任何问题,您可以将实际对象发送到该方法。如果发送对象类型,则会在字典

中获取类型作为值