vendredi 29 septembre 2023

Propertyinfo not returning properties of a nested type

I am trying to retrieve the properties of a nested type. Here is the code to retrieve properties, including nested properties using recursion. All of the properties are returned but the properties of the nested property are not returning after it hits the getproperties() method.


 public class Employee
    {
    
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
        public Address Address { get; set; }
        public DateTime BirthDate { get; set; }
        public IEnumerable<Paycheck> Paychecks { get; set; }
        public string SocialSecurityNumber { get; set; }

    }

public class Address
    {

        public string AddressOne { get; set; }
        public string AddressTwo {get;set;}
        public string City { get; set; }
        public string State { get; set; }
        public Zip Zip { get; set; }

    }

public List<LoggedObjectProperty> GetItems<T>(T obj)
        {
          
            var ret = new List<LoggedObjectProperty>();

            PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            
            foreach (PropertyInfo property in properties)
            {
                
              
                    if (property.PropertyType.IsClass && property.PropertyType != typeof(string))
                    {
                       
                        if (obj == null) { return null; }

                        Type type = obj.GetType();

                        PropertyInfo info = type.GetProperty(property.Name);

                        if (info == null) { return null; }
                        var v = info.GetValue(obj, null);

                        if (v != null)
                            GetItems(v);

                    }

                }

            }

            return ret;

        }



I expected to see the properties of the nested type but no properties were returned.




Aucun commentaire:

Enregistrer un commentaire