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