2013-09-24 31 views
1

我有一個集合中的項目我需要使用反射進行修改 - 我正在使用反射,因爲我直到運行時才知道泛型集合的確切類型。我知道如何使用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 });        
    } 

} 
+2

你甚至知道你的收藏是可以修改的嗎? –

+0

什麼類型是'businessObjectCollection'? IEnumerable不能被修改。如果您想假定您有能力修改它,則必須將IEnumerable更改爲IList或ICollection。 –

+4

你在一個集合中設置一個項目,同時用foreach遍歷它;那就是糟糕的juju,並且很可能會以異常告終,「C#集合已被修改;枚舉操作可能無法執行」。 –

回答

0

嘛,你使用get_Item找回它,所以你應該能夠調用set_Item設置它:

businessObjectCollection.GetType().GetMethod("set_Item").Invoke(businessObjectCollection, new object[] { 1, replacementEntity }); 

注意,這會爆炸,如果集合是一類不支持索引訪問。

+0

結束了使用這個 - 偉大的工作爲我的目的。 –

2
collection.GetType().GetProperty("Item").SetValue(collection, o, new object[] { 1 }) 
1

而不是嘗試修改枚舉,您可以用一個新的可執行內置替換的枚舉替換它。這真的取決於你之後用YMMV做什麼。

IEnumerable newCollection = businessObjectCollection.Cast<object>().Select((o) => 
{ 
    Type t = o.GetType(); 
    PropertyInfo identifierProperty = o.GetType().GetProperty("Identifier"); 
    long entityID = (long)identifierProperty.GetValue(o, null); 

    if (replacementEntity.Identifier == entityID) 
    { 
     return replacementEntity; 
    } 
    return o; 
}); 
+0

哦,這是SOOOO關閉!它正在做我正在尋找的東西,除了我不能將這個新的IEnumerable分配給我的次要對象來替換集合(發生異常,指出IEnumerable類型的對象不能轉換爲通用列表類型)。有沒有辦法將此IEnumerable轉換爲我在運行時查找的類型的通用列表? –

+0

我想我應該知道更多關於你在做什麼。如果此操作的結果稍後需要變化,那麼看起來你選擇的路線會更好。它乞求的問題爲什麼對象是從列表 - > enumerable - >列表,但這不是真的在回答這個問題的範圍:) – OlduwanSteve

相關問題