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
集合属性?
遗憾的是它仍然没有更新'targetResource.propertyName'新创建的一个(targetResource.propertyName.Count =关口!计数)。 – 2011-04-15 14:25:58
在这里可以正常工作 – Magnus 2011-04-15 14:34:24
嗯,是的。好吧,我的错误。我的座位和我的键盘之间出现错误。 – 2011-04-15 15:02:56