我在集合中有一个项目需要使用反射进行修改 - 我正在使用反射,因为直到运行时我才知道通用集合的确切类型。
我知道如何使用 SetValue() 方法来设置通过集合检索到的属性的值,但是我可以使用 SetValue() 在集合中设置实际对象吗?
IEnumerable businessObjectCollection = businessObject as IEnumerable;
foreach (Object o in businessObjectCollection)
{
// I want to set the "o" here to some replacement object in the collection if
// a property on the object equals something
Type t = o.GetType();
PropertyInfo identifierProperty = o.GetType().GetProperty("Identifier");
long entityID = (long)identifierProperty.GetValue(o, null);
if (replacementEntity.Identifier == entityID)
{
// IN THIS CASE: set "o" to be the replacementEntity object
// defined somewhere else.
// I can retrieve the object itself using this code, but
// would I set the object with SetValue?
object item = businessObjectCollection.GetType().GetMethod("get_Item").Invoke(businessObjectCollection, new object[] { 1 });
}
}