如何在编译时创建List 并通过System.Reflection.PropertyInfo复制项目

我遇到了一些相当复杂的东西。 如果有人能提供帮助,我将不得不承担责任。

1)我必须在编译时创建一个未知类型的List 。 我已经实现了。

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

“temptype”是已经获取的自定义类型。

2)现在我有PropertyInfo对象,我必须将所有项目复制到我刚刚创建的实例“objectList”

3)然后我需要迭代并访问“objectList”的项目,就像它是“System.Generic.List”一样。

简而言之,使用reflection我需要提取一个列表属性并将其作为实例供进一步使用。 您的建议将不胜感激。 提前致谢。

Umair

许多.NETgenerics集合类也实现了它们的非generics接口。 我会利用这些来编写代码。

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

你认为这对你有帮助吗? 从另一个集合更新集合的有效方法

我想出了类似的东西。 我从NullSkull借用了SetProperties()方法并编写了一个调用NullSkull SetProperties()的简单方法:

  public static List CopyList(List fromList, List toList) { PropertyInfo[] fromFields = typeof(T).GetProperties(); PropertyInfo[] toFields = typeof(U).GetProperties(); fromList.ForEach(fromobj => { var obj = Activator.CreateInstance(typeof(U)); Util.SetProperties(fromFields, toFields, fromobj, obj); toList.Add((U)obj); }); return toList; } 

…所以使用一行代码,我可以检索一个List填充了List按名称匹配的值,如下所示:

 List des = CopyList(source_list, new List()); 

就性能而言,我没有测试它,因为我的要求需要小列表。