2011-04-15 19 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

相关问题