3

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.

4

1 回答 1

5

根据您尝试投射Eclipsys.Enterprise.Entities.Registration.VisitLite到的第一个异常List<>。我认为这是你的问题。

尝试这个:

 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 });
 }
于 2013-09-24T17:07:31.780 回答