如何使用reflection将新项添加到集合中

我正在尝试使用reflection将未知对象添加到未知集合类型,并且当我实际执行“添加”时,我遇到exception。 我想知道是否有人可以指出我做错了什么或另类?

我的基本方法是迭代通过reflection检索的IEnumerable,然后将新项添加到第二个集合中,我稍后可以将其用作替换集合(包含一些更新的值):

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 }); } 

例外是:

“Eclipsys.Enterprise.Entities.Registration.VisitLite”类型的对象无法转换为“System.Collections.Generic.List`1 [Eclipsys.Enterprise.Entities.Registration.VisitLite]”类型。

如果我使用这行代码代替Add() ,我得到一个不同的exception:

 newCollection.Add(entity); 

例外是:

值“”不是“System.Collections.Generic.List`1 [Eclipsys.Enterprise.Entities.Registration.VisitLite]”类型,并且不能在此通用集合中使用。

根据第一个例外,您尝试将Eclipsys.Enterprise.Entities.Registration.VisitLiteList<> 。 我认为这是你的问题。

试试这个:

  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 }); }