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

Dus*_*oed 3 .net c# 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 });
}
Run Code Online (Sandbox Code Playgroud)

例外是:

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

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

newCollection.Add(entity); 
Run Code Online (Sandbox Code Playgroud)

例外是:

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

Dil*_*hod 5

根据第一种例外您要投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 });
 }
Run Code Online (Sandbox Code Playgroud)