0

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

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

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

4

1 回答 1

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

所以对象不会有任何问题,您可以将实际对象发送到该方法。如果您发送对象类型,那么您将在字典中获得类型作为值

于 2012-08-06T12:00:46.647 回答