编辑:请往前走,这里没什么可看的。
这个问题的解决方案与反射无关,一切都与我没有注意基类中集合属性的实现有关。
我正在尝试使用以下方法使用反射将项目添加到集合中:
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 集合属性中?
请您参考如下方法:
试试这个:
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");
}
}
