创建使用反射泛型列表

编程入门 行业动态 更新时间:2024-10-21 18:35:26
本文介绍了创建使用反射泛型列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个使用反射来设置对象A从对象B.属性功能 在一个点上,我需要实例化一个泛型集合。但是,我无法得到它的工作。以下是我现在有:

I have a function that uses reflection to set properties of object A from object B. At one point, I need to instantiate a generic collection. However, I am unable to get it working. Here is what I have now:

IList list = destProperty.PropertyType.GetGenericTypeDefinition() .MakeGenericType(destProperty.PropertyType.GetGenericArguments()) .GetConstructor(Type.EmptyTypes) .Invoke(null) as IList;

我想设置destProperty的价值。它必须是一个列表 在运行时,destProperty的类型的ICollection&LT的;>。我想,这是怎么回事是,因为ICollection的是一个接口,它没有构造函数。什么是正确的方式来实例化它呢?

I am trying to set the value of the destProperty. It has to be a List At runtime, the destProperty is of type ICollection<>. I think what's happening is that since ICollection is an interface, it has no constructor. What is the proper way to instantiate it then?

谢谢!

推荐答案

我重新写你的code,进入一个例子的形式(希望符合你想做什么!=),尝试更清楚的问题是什么:

I've re-written your code, into the form of an example (hopefully that matches what you're trying to do! =), to try and make it clearer what the problem is:

public class Program { public struct MyType { public ICollection<string> MyProperty { get; set; } } static void Main(string[] args) { var type = typeof(MyType); var properties = type.GetProperties(); var destProperty = properties[0]; var genericTypeDefinition = destProperty.PropertyType.GetGenericTypeDefinition(); var madeGenericType = genericTypeDefinition.MakeGenericType(destProperty.PropertyType.GetGenericArguments()); var ctor = madeGenericType.GetConstructor(Type.EmptyTypes); } }

如果你把一个断点上的倒数第二个括号,你会看到男星回来为空,其中是因为,当你正确地推测,的ICollection&LT; T&GT; 没有任何构造函数,由于它是一个界面

If you put a breakpoint on the penultimate brace you'll see that ctor comes back as null, which is because, as you correctly surmised, ICollection<T> doesn't have any constructors due to it being an interface.

正因为如此,有这样做,因为没有固有的方式说不超通用的方式有什么的的ICollection&LT最好的执行情况; T&GT; 来使用在这种情况下。你需要做出决定和新一,根据你反映回来的信息。

Because of this, there's no "super-generic" way of doing this because there's no inherent way to say "what's the best implementation of ICollection<T> to use in this situation". You'll need to make that decision and new one, based on the information you get back from reflection.

更多推荐

创建使用反射泛型列表

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

发布评论

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

>www.elefans.com

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