我有一個集合中的項目我需要使用反射進行修改 - 我正在使用反射,因爲我直到運行時才知道泛型集合的確切類型。我知道如何使用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 });
}
}
你甚至知道你的收藏是可以修改的嗎? –
什麼類型是'businessObjectCollection'? IEnumerable不能被修改。如果您想假定您有能力修改它,則必須將IEnumerable更改爲IList或ICollection。 –
你在一個集合中設置一個項目,同時用foreach遍歷它;那就是糟糕的juju,並且很可能會以異常告終,「C#集合已被修改;枚舉操作可能無法執行」。 –