I'm looping through an xml document in order to set properties of an object. I have one property that is actually a Collection of other custom objects. I'm looping through the child nodes and setting the values of these objects. Each time through, the object is populated correctly, however, when I run the "Invoke" on the "Add" method, it sets all objects in the Collection equal to the last object populated. I end up with the correct number of child objects, but they all have the same value as the last one populated.
type is my object type.
obj is the main object to be populated
SetObjectAttributesFromXml is the method being called that loops through the XML attributes. This is working correctly.
propValueType is a Collection type of my base object
Expand|Select|Wrap|Line Numbers
- object objChild = Activator.CreateInstance(type);
- object objList = Activator.CreateInstance(propValueType);
- Type objType = objList.GetType();
- MethodInfo methInfo = objType.GetMethod("Add");
- foreach (XmlNode subChild in childNode.ChildNodes)
- {
- object objReturnVal = new object();
- objReturnVal = SetObjectAttributesFromXml(objChild, subChild);
- // at this point, objReturnVal is properly populated from my XML
- methInfo.Invoke(objList, new object[] { objReturnVal });
- // first time through, objList shows as a collection with proper values
- // subsequent times through, objList shows as the correct size,
- // however all values are the same as the last processed object
- objReturnVal = null;
- }
- propInfoObj.SetValue(obj, objList, null);