我遇到了一些相当复杂的事情。如果有人可以提供帮助,我将不胜感激。
1)我必须在编译时创建一个未知类型的List。我已经实现了。
Type customList = typeof(List<>).MakeGenericType(tempType);
object objectList = (List<object>)Activator.CreateInstance(customList);
“temptype”是已经获取的自定义类型。
2)现在我有PropertyInfo
object 这是我必须将所有项目复制到我刚刚创建的实例“objectList”的列表
3)然后我需要迭代并访问“objectList”的项目,就好像它是“System.Generic.List”一样。
长话短说,使用反射我需要提取一个列表属性并将其作为实例以供进一步使用。您的建议将不胜感激。提前致谢。
Umair
许多 .NET 泛型集合类还实现其非泛型接口。我会利用这些来编写您的代码。
// 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()); }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)