Using reflection to get values from properties from a list of a class

后端 未结 2 1043
感动是毒
感动是毒 2020-12-07 00:27

I am trying to get the values from objects inside a list which is part of a main object.

I have the main object which contains various properties which can be collec

相关标签:
2条回答
  • 2020-12-07 01:02

    See if something like this helps you in the right direction: I got the same error a while back and this code snipped solved my issue.

    PropertyInfo[] properties = MyClass.GetType().GetProperties();
    foreach (PropertyInfo property in properties)
    {
      if (property.Name == "MyProperty")
      {
       object value = results.GetType().GetProperty(property.Name).GetValue(MyClass, null);
       if (value != null)
       {
         //assign the value
       }
      }
    }
    
    0 讨论(0)
  • 2020-12-07 01:18

    To Get/Set using reflection you need an instance. To loop through the items in the list try this:

    PropertyInfo piTheList = MyObject.GetType().GetProperty("TheList"); //Gets the properties
    
    IList oTheList = piTheList.GetValue(MyObject, null) as IList;
    
    //Now that I have the list object I extract the inner class and get the value of the property I want
    
    PropertyInfo piTheValue = piTheList.PropertyType.GetGenericArguments()[0].GetProperty("TheValue");
    
    foreach (var listItem in oTheList)
    {
        object theValue = piTheValue.GetValue(listItem, null);
        piTheValue.SetValue(listItem,"new",null);  // <-- set to an appropriate value
    }
    
    0 讨论(0)
提交回复
热议问题