问题描述
我正在尝试使用反射将未知对象添加到未知集合类型,并且在我实际执行添加"时遇到异常.我想知道是否有人可以指出我在做错什么还是其他选择?
I'm trying to use reflection to add an unknown object to an unknown collection type, and I'm getting an exception when I actually perform the "Add". I wonder if anyone can point out what I'm doing wrong or an alternative?
我的基本方法是遍历通过反射检索的IEnumerable,然后将新项目添加到辅助集合中,以后可以用作替换集合(包含一些更新值):
My basic approach is to iterate through an IEnumerable which was retrieved through reflection, and then adding new items to a secondary collection I can use later as the replacement collection (containing some updated values):
IEnumerable businessObjectCollection = businessObject as IEnumerable;
Type customList = typeof(List<>)
.MakeGenericType(businessObjectCollection.GetType());
var newCollection = (System.Collections.IList)
Activator.CreateInstance(customList);
foreach (EntityBase entity in businessObjectCollection)
{
// This is the area where the code is causing an exception
newCollection.GetType().GetMethod("Add")
.Invoke(newCollection, new object[] { entity });
}
例外是:
如果我将这行代码用于 Add()
,则会得到另一个异常:
If I use this line of code for the Add()
instead, I get a different exception:
newCollection.Add(entity);
例外是:
推荐答案
根据第一个异常,您试图将 Eclipsys.Enterprise.Entities.Registration.VisitLite
强制转换为 List<>;
.我认为那是你的问题.
According to a first exception you are trying to cast Eclipsys.Enterprise.Entities.Registration.VisitLite
to List<>
. I think that's your problem.
尝试一下:
businessObject = //your collection;
//there might be two Add methods. Make sure you get the one which has one parameter.
MethodInfo addMethod = businessObject.GetType().GetMethods()
.Where(m => m.Name == "Add" && m.GetParameters().Count() == 1).FirstOrDefault();
foreach(object obj in businessObject as IEnumerable)
{
addMethod.Invoke(businessObject, new object[] { obj });
}
这篇关于如何使用反射将新项目添加到集合中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!