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

编程入门 行业动态 更新时间:2024-10-11 11:15:58
本文介绍了如何使用反射将新项目添加到集合中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

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

本文发布于:2023-11-12 11:19:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581352.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   反射   新项目

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!