How to use reflection to add a new item to a collection

浪尽此生 提交于 2020-01-04 02:07:24

问题


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?

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

The exception is:

Object of type 'Eclipsys.Enterprise.Entities.Registration.VisitLite' cannot be converted to type 'System.Collections.Generic.List`1[Eclipsys.Enterprise.Entities.Registration.VisitLite]'.

If I use this line of code for the Add() instead, I get a different exception:

newCollection.Add(entity); 

The exception is:

The value "" is not of type "System.Collections.Generic.List`1[Eclipsys.Enterprise.Entities.Registration.VisitLite]" and cannot be used in this generic collection.


回答1:


According to a first exception you are trying to cast Eclipsys.Enterprise.Entities.Registration.VisitLite to List<>. I think that's your problem.

Try this:

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


来源:https://stackoverflow.com/questions/18987104/how-to-use-reflection-to-add-a-new-item-to-a-collection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!