mercredi 10 juin 2020

How Get Property Value of Nested Classes using reflection

Currently in my class DataEntries I have to sub class, UserObjects and TagObjects. I am trying to access the properties of TagObjects in my test class.. I have another class where these objects are serialized which is DataProvider class. I ma using this Reflection helper but I am unable to pick the properties

//Reflection Helper

    public static class ReflectionHelper
    {
        public static Object GetPropValue(this Object obj, String propName)
        {
            string[] nameParts = propName.Split('.');
            if (nameParts.Length == 1)
            {
                return obj.GetType().GetProperty(propName).GetValue(obj, null);
            }

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

                Type type = obj.GetType();
                PropertyInfo info = type.GetProperty(part);
                if (info == null) { return null; }

                obj = info.GetValue(obj, null);
            }
            return obj;
        }
    }
 public class UserObjects
        {
            public string UserId { get; set; }
            public string UserId2 { get; set; }

        }


       public class TagObjects
       {
            public int id { get; set; }
            public string name { get; set; }
            public int type { get; set; }
            public TagObjects Child { get; set; }

       }

//Test class usage

public class TestClass
{
     DataProvider dataprovider = new DataProvider();

      [Test]
       public void GetTagList()
    {
        var TagId = dataprovider.GetPropValue("DataEntries.id");

    }
}

Not sure if this will help up Here is my DataProvider class and method for to help place my query parameters when calling the API

public class DataProvider {

  public DataEntries DataEntries { get; private set; }

   public DataProvider ()
        {
            DataEntries = new DataEntries();
        }

 public Dictionary<string, object> DataProviderQueryParams(dynamic matchKey)
        {
             DataEntries dataEntries = new DataEntries();
            string data = JsonConvert.SerializeObject(dataEntries);
            Dictionary<string, object> Items = JsonConvert.DeserializeObject<Dictionary<string, object>>(data);
            if (Items.TryGetValue(matchKey, out object value))
            {

                return new Dictionary<string, object> { { matchKey, value } };
            }


            return null;
        }
}




Aucun commentaire:

Enregistrer un commentaire