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

后端 未结 2 1057
感动是毒
感动是毒 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: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
    }
    

提交回复
热议问题