使用反射在运行时创建动态泛型
我正在尝试转换字典< 动态,动态 >通过检查键和值的类型并使用反射创建适当类型的新字典,将其转换为静态类型的字典。如果我知道键和值类型,我可以执行以下操作:
Type dictType = typeof(Dictionary<,>);
newDict = Activator.CreateInstance(dictType.MakeGenericType(new Type[] { keyType, valueType }));
但是,我可能需要创建一个 Dictionary< MyKeyType、动态 >如果值不都是同一类型,并且我无法弄清楚如何指定动态类型,因为
typeof(dynamic)
这是不可行的。
我将如何去做这件事,和/或者是否有更简单的方法来完成我想做的事情?
I'm trying to convert a Dictionary< dynamic, dynamic > to a statically-typed one by examining the types of the keys and values and creating a new Dictionary of the appropriate types using Reflection. If I know the key and value types, I can do the following:
Type dictType = typeof(Dictionary<,>);
newDict = Activator.CreateInstance(dictType.MakeGenericType(new Type[] { keyType, valueType }));
However, I may need to create, for example, a Dictionary< MyKeyType, dynamic > if the values are not all of the same type, and I can't figure out how to specify the dynamic type, since
typeof(dynamic)
isn't viable.
How would I go about doing this, and/or is there a simpler way to accomplish what I'm trying to do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
C# 编译器将 System.Object 作为“动态”类型发出。 “动态”是特定于语言的构造,并且在公共语言基础结构中没有对应的类型。因此,您将无法使用反射来创建“动态”,也无法使用“动态”作为泛型类型参数。
字典<动态,动态>实际上是一个 Dictionary
附带说明一下,编译器还将在“动态”字段、参数等上发出一个属性 DynamicAttribute;它允许人们使用程序集的元数据来区分 System.Object 和“动态”。例如,这就是 IntelliSense 将方法的参数显示为来自程序集引用的动态参数的方式。
The C# compiler emits System.Object as the type for "dynamic". "dynamic" is a language-specific construct and has no corresponding type in the Common Language Infrastructure. As such, you won't be able to use reflection to create a "dynamic" nor use "dynamic" as a generic type parameter.
A Dictionary<dynamic, dynamic> is really a Dictionary<object, object>. What "dynamic" means to the compiler is simply late-bind any member accesses for the object using reflection (the implementation of which lies in the Microsoft.CSharp assembly in case you're curious).
On a side note, the compiler will also emit an attribute, DynamicAttribute, on fields, parameters, etc. that are "dynamic"; that allows people consuming the assembly's metadata to distinguish between a System.Object and a "dynamic". This is how IntelliSense shows a method's parameter as dynamic from an assembly reference, for example.
这实际上创建了一个
Dictionary
我从使用动态而不是对象中看到的唯一用途是在代码输入过程中,您可以使用 dic["some"].MyDynProperty.... 但如果您使用 Activator 创建对象,它将返回对象,因此在代码输入中没有用...
This actually creates a
Dictionary<Object, Object>
The only use I can see from using dynamic instead of object is during code typing you can use dic["some"].MyDynProperty.... but if you create you object with Activator it will return Object so no use in code typing...