mardi 2 août 2016

Get Property Value of Nested Classes is always null

I have following two classes

public class Family
{
    public string ChildName { get; set; }
}

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Family Child { get; set; }

}

I have an instance of Employee class as follows.

     Employee employee = new Employee();
     employee.Name = "Ram";
     employee.Id = 77;
     employee.Child = new Family() { ChildName = "Lava" };

I have a method which gets the property value based on the property name as follows:

public static object GetPropertyValue(object src, string propName)
{
  string[] nameParts = propName.Split('.');

 if (nameParts.Length == 1)
  {
    return src.GetType().GetRuntimeProperty(propName).GetValue(src, null);
  }

foreach (String part in nameParts)
{
    if (src == null) { return null; }

    Type type = src.GetType();

    PropertyInfo info = type.GetRuntimeProperty(part);

    if (info == null)
    { return null; }

    src = info.GetValue(src, null);
   }
   return src;
}

In the above method,when I try to get property value of nested class like

GetPropertyValue(employee2, "employee2.Child.ChildName")  

or

GetPropertyValue(GetPropertyValue(employee2, "Family"), "ChildName"

doesn't return any value because type.GetRuntimeProperty(part) is always null.

Is there any way to fix this problem?





Aucun commentaire:

Enregistrer un commentaire