2011-04-15 27 views
1

編輯:請移動,沒有什麼在這裏看到。添加一個項目到一個通用名單<T>與反射

這個問題的解決方案與Reflection沒有任何關係,並且我沒有注意到基類中collection屬性的實現。


我想使用反射使用下面的方法的項目添加到集合:

public void AddReferenceToCollection(object targetResource, string propertyName, object resourceToBeAdded) 
{ 
    Type targetResourceType = targetResource.GetType(); 
    PropertyInfo collectionPropertyInfo = targetResourceType.GetProperty(propertyName); 

    // This seems to get a copy of the collection property and not a reference to the actual property 
    object collectionPropertyObject = collectionPropertyInfo.GetValue(targetResource, null); 
    Type collectionPropertyType = collectionPropertyObject.GetType(); 
    MethodInfo addMethod = collectionPropertyType.GetMethod("Add"); 

    if (addMethod != null) 
    { 
     // The following works correctly (there is now one more item in the collection), but collectionPropertyObject.Count != targetResource.propertyName.Count 
     collectionPropertyType.InvokeMember("Add", System.Reflection.BindingFlags.InvokeMethod, null, collectionPropertyObject, new[] { resourceToBeAdded }); 
    } 
    else 
    { 
     throw new NotImplementedException(propertyName + " has no 'Add' method"); 
    } 
} 

然而,似乎調用targetResource.GetType().GetProperty(propertyName).GetValue(targetResource, null)返回targetResource.propertyName,而不是一個副本引用它,因此後續調用collectionPropertyType.InvokeMember會影響副本而不是引用。

如何將resourceToBeAdded對象添加到targetResource對象的propertyName集合屬性?

回答

4

試試這個:

public void AddReferenceToCollection(object targetResource, string propertyName, object resourceToBeAdded) 
{ 
    var col = targetResource.GetType().GetProperty(propertyName).GetValue(targetResource, null) as IList; 
    if(col != null) 
     col.Add(resourceToBeAdded); 
    else 
     throw new InvalidOperationException("Not a list"); 
} 

編輯:測試使用

void Main() 
{ 

    var t = new Test(); 
    t.Items.Count.Dump(); //Gives 1 
    AddReferenceToCollection(t, "Items", "testItem"); 
    t.Items.Count.Dump(); //Gives 2 
} 
public class Test 
{ 
    public IList<string> Items { get; set; } 

    public Test() 
    { 
     Items = new List<string>(); 
     Items.Add("ITem"); 
    } 
} 
+0

遺憾的是它仍然沒有更新'targetResource.propertyName'新創建的一個(targetResource.propertyName.Count =關口!計數)。 – 2011-04-15 14:25:58

+0

在這裏可以正常工作 – Magnus 2011-04-15 14:34:24

+0

嗯,是的。好吧,我的錯誤。我的座位和我的鍵盤之間出現錯誤。 – 2011-04-15 15:02:56

相關問題