编辑:请继续前进,这里什么也看不到。

这个问题的解决方案与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对象添加到propertyName对象的targetResource集合属性中?

最佳答案

尝试这个:

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");
    }
}

10-06 12:06