lundi 15 juillet 2019

Find Property value in a nested object using PropertyInfo & Reflection

here is a sample of a code that let me get the value using an object's property name, it works with flatten objects.

        public static object GetPropValue<T>(T obj, String propName)
        {
           if (obj == null) { return null; }

           Type type = typeof(T);
           PropertyInfo info = type.GetProperty(propName);
           if (info == null) { return null; }

           return info.GetValue(obj);
        }


How can I make this work if T happens to be a nested object? Here is my attempt so far with recursive but no luck yet.

        public static object GetPropValue<T>(T obj, String propName)
        {
           if (obj == null) { return null; }

           Type type = typeof(T);

           foreach(PropertyInfo property in  type.GetProperties(BindingFlags.Public))
           {
              if(!property.PropertyType.IsValueType)
              {
                 var nestedObj = (from subObj in obj select property.GetValue(subOjb));

                 //recursive call where object pass in is
                 //one of the nested property object.
                 GetPropValue(nestedObj, propName);

              }
              else
              {
                 return property.GetValue(obj);
              }
           }

        }


In this case, for example a nested object can be:

    public class A{
       public string property1 {get; set;}
       public B property2 {get;set;}
    }

    public class B{
       public string property3 {get;set;
       public C property4 {get;set;}
    }

    public class C{
       public string property5 {get;set;}
    }






Aucun commentaire:

Enregistrer un commentaire