使用Reflection </t>将项添加到通用List <t>

时间:2011-04-15 13:48:20

标签: c# reflection

编辑:请继续前进,没有什么可看的。

这个问题的解决方案与Reflection没有任何关系,与我无关,没有注意基类中集合属性的实现。


我正在尝试使用Reflection使用以下方法将项添加到集合中:

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对象添加到propertyName对象的targetResource集合属性中?

1 个答案:

答案 0 :(得分: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");
    }
}