mardi 6 avril 2021

How to get/set value of properties using string property paths?

Let's say we have a class Root that has BasicDetails class property and then basicDetails has two properties. A string "Name" and a dynamic object called "CustomAttributes".

I want to get the value in the following manner:

  var root = new Root();
  root.BasicDetails.Name = "Samurai";
  root.BasicDetails.CustomAttributes.phone = "12345";
  string res1 = GetDeepPropertyValue(root, "BasicDetails.CustomAttributes.Phone").ToString();
  string res2 = GetDeepPropertyValue(root, "BasicDetails.Name").ToString();

The following is the code I have tried (based on another answer on SO):

public static object GetDeepPropertyValue(object src, string propName)
{
    if (propName.Contains('.'))
    {
        string[] Split = propName.Split('.');
        string RemainingProperty = propName.Substring(propName.IndexOf('.') + 1);
        return GetDeepPropertyValue(src.GetType().GetProperty(Split[0]).GetValue(src, null), RemainingProperty);
    }
    else
        return src.GetType().GetProperty(propName).GetValue(src, null);
}

The following are the classes:

public class Root
{
    public Root()
    {
        BasicDetails = new BasicDetails();
    }
    public BasicDetails BasicDetails { get;set;}
}
public class BasicDetails
{
    public BasicDetails()
    {
        CustomAttributes = new ExpandoObject();
    }
    public string Name { get; set; }
    public dynamic CustomAttributes { get; set; }
}

The function that I have tried is throwing null reference error. Unfortunately I do not understand reflection too well so at the moment I am monkey patching. If someone could please explain c#how this can be done it would be great. Thank you in advance.





Aucun commentaire:

Enregistrer un commentaire