c# - How to use reflection to add a new item to a collection -


i'm trying use reflection add unknown object unknown collection type, , i'm getting exception when perform "add". wonder if can point out i'm doing wrong or alternative?

my basic approach iterate through ienumerable retrieved through reflection, , adding new items secondary collection can use later replacement collection (containing updated values):

ienumerable businessobjectcollection = businessobject ienumerable; type customlist = typeof(list<>)        .makegenerictype(businessobjectcollection.gettype()); var newcollection = (system.collections.ilist)           activator.createinstance(customlist);  foreach (entitybase entity in businessobjectcollection) { // area code causing exception     newcollection.gettype().getmethod("add")          .invoke(newcollection, new object[] { entity }); } 

the exception is:

object of type 'eclipsys.enterprise.entities.registration.visitlite' cannot converted type 'system.collections.generic.list`1[eclipsys.enterprise.entities.registration.visitlite]'.

if use line of code add() instead, different exception:

newcollection.add(entity);  

the exception is:

the value "" not of type "system.collections.generic.list`1[eclipsys.enterprise.entities.registration.visitlite]" , cannot used in generic collection.

according first exception trying cast eclipsys.enterprise.entities.registration.visitlite list<>. think that's problem.

try this:

 businessobject = //your collection;  //there might 2 add methods. make sure 1 has 1 parameter.  methodinfo addmethod = businessobject.gettype().getmethods() .where(m => m.name == "add" && m.getparameters().count() == 1).firstordefault();  foreach(object obj in businessobject ienumerable)  {      addmethod.invoke(businessobject, new object[] { obj });  } 

Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -