如何创建List<编译时类型未知>并通过 System.Reflection.PropertyInfo 复制项目编译时类型未知>
我遇到了一些相当复杂的事情。如果有人可以提供帮助,我将不胜感激。
1)我必须创建一个列表<>编译时类型未知。我已经实现了。
Type customList = typeof(List<>).MakeGenericType(tempType);
object objectList = (List<object>)Activator.CreateInstance(customList);
“temptype”是已经获取的自定义类型。
2)现在我有 PropertyInfo
对象,它是我必须将所有项目复制到我刚刚创建的“objectList”实例的列表
3)然后我需要迭代并访问 的项目“objectList”就好像它是一个“System.Generic.List”。
长话短说,使用反射我需要提取一个列表属性并将其作为实例以供进一步使用。您的建议将不胜感激。提前致谢。
乌迈尔
I have come across something pretty complex. I would be obliged if anyone can help.
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" is the custom type thats been already fetched.
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) 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
许多 .NET 泛型集合类还实现其非泛型接口。我会利用这些来编写您的代码。
Many of the .NET generic collection classes also implement their non-generic interfaces. I'd make use of these to write your code.
您认为这对您有帮助吗? 从另一个集合更新一个集合的有效方法< /a>
Do you think this would help you? Efficient way of updating a collection from another collection
我想出了类似的东西。我从 NullSkull 并编写了一个调用 NullSkull
SetProperties()
的简单方法:...所以我可以通过一行代码检索
List
,其中按名称从List
填充匹配值,如下所示:就性能而言,我没有不要测试它,因为我的要求需要小列表。
I came up with something similar. I borrowed the
SetProperties()
method from NullSkull and wrote a simple method that calls the NullSkullSetProperties()
:...so with one line of code I can retrieve a
List<desired class>
populated with matching values by name fromList<source class>
as follows:As far as performance goes, I didn't test it, as my requirements call for small lists.