如何创建一个列表<未知类型在编译时间>复制和通过System.Reflection.PropertyInfo项目 [英] How to create a List<unknown type at compile time> and copy items via System.Reflection.PropertyInfo

查看:285
本文介绍了如何创建一个列表<未知类型在编译时间>复制和通过System.Reflection.PropertyInfo项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所遇到的事情相当复杂。我将不得不如果有人能帮助

I have come across something pretty complex. I would be obliged if anyone can help.

1)我要创建一个列表<>在编译时未知类型。 。我已经实现了

1) I have to create a List<> of unknown type at compile time. That I have already achieved.

 Type customList = typeof(List<>).MakeGenericType(tempType);
 object objectList = (List<object>)Activator.CreateInstance(customList);



temptype是自定义类型,多数民众赞成了已获取的。

"temptype" is the custom type thats been already fetched.

2),现在我有的PropertyInfo 对象,它是一个列表,从中我要复制所有项目到我刚才创建链表类的实例

2) Now I have PropertyInfo object which is that list from which I have to copy all items to the the instance that I have just created "objectList"

3)然后我需要遍历并访问链表类,就好像它是一个System.Generic.List的项目。

3) Then I need to iterate and access the items of "objectList" as if it were a "System.Generic.List".

切割长话短说,使用反射我需要提取一个属性就是一个列表,并把它作为进一步用一个实例。您的建议将不胜感激。先谢谢了。

Cutting long story short, using reflection I need to extract a property that is a list and have it as an instance for further use. Your suggestions would be appreciated. Thanks in Advance.

Umair

推荐答案

许多.NET的泛型集合类也实现了非通用接口。我会利用这些编写代码

Many of the .NET generic collection classes also implement their non-generic interfaces. I'd make use of these to write your code.

// Create a List<> of unknown type at compile time.
Type customList = typeof(List<>).MakeGenericType(tempType);
IList objectList = (IList)Activator.CreateInstance(customList);

// Copy items from a PropertyInfo list to the object just created
object o = objectThatContainsListToCopyFrom;
PropertyInfo p = o.GetType().GetProperty("PropertyName");
IEnumerable copyFrom = p.GetValue(o, null);
foreach(object item in copyFrom) objectList.Add(item); // Will throw exceptions if the types don't match.

// Iterate and access the items of "objectList"
// (objectList declared above as non-generic IEnumerable)
foreach(object item in objectList) { Debug.WriteLine(item.ToString()); }

这篇关于如何创建一个列表&LT;未知类型在编译时间&gt;复制和通过System.Reflection.PropertyInfo项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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