向通用列表中添加项<与反思
本文关键字:添加 列表 | 更新日期: 2023-09-27 17:50:13
编辑:请移开,这里没什么可看的
这个问题的解决方案与反射无关,而与我没有注意到基类中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
集合属性中?
试试这个:
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");
}
}