如何使用反射将新项目添加到集合中 [英] How to use reflection to add a new item to a collection

查看:38
本文介绍了如何使用反射将新项目添加到集合中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用反射将未知对象添加到未知集合类型,并且在我实际执行添加"时遇到异常.我想知道是否有人可以指出我在做错什么还是其他选择?

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?

我的基本方法是遍历通过反射检索的IEnumerable,然后将新项目添加到辅助集合中,以后可以用作替换集合(包含一些更新值):

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

例外是:

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

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

如果我将这行代码用于 Add(),则会得到另一个异常:

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

newCollection.Add(entity); 

例外是:

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

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

推荐答案

根据第一个异常,您试图将 Eclipsys.Enterprise.Entities.Registration.VisitLite 强制转换为 List<>; .我认为那是你的问题.

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

尝试一下:

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

这篇关于如何使用反射将新项目添加到集合中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆