使用 C#“动态”实例化关键词
我见过很多这个工具的例子,它抽象出了反射的繁琐语法。然而,没有一个证明未知类型的实例化。可以安全地假设这对于“动态”来说是不可能的吗?
I've seen many examples of this tool which abstracts away the cumbersome syntax of Reflection. However none demonstrate instantiation of an unknown type. Is it safe to assume this isn't possible with "dynamic"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从逻辑上讲,不可能实例化一个未知类型——要实例化一个类型,某物必须知道它是什么。
dynamic
对于操作未知类型的值很有用(假设它能够执行某些操作,如果实际上不可能,则这些操作将在运行时失败)。但是,要实例化任何类型,您要么需要使用编译时实例化(例如使用 C# 构造函数调用),要么需要一个与以下内容对应的Type
实例您想要的类型。Logically, it's impossible to instantiate an unknown type -- to instantiate a type, something must know what it is.
dynamic
is useful for manipulating values of an unknown type (by assuming that it is capable of certain operations, which will fail at runtime if they are in fact not possible). To instantiate any type, however, you either need to use compile-time instantiation (e.g. using a C# constructor call), or else you need an instance ofType
that corresponds to your desired type.编译器可以使用dynamic关键字,以便dlr构造一个类型,但它被设计为后期绑定构造函数的参数而不是要构造的类型。开源框架 ImpromptuInterface 抽象了 dlr 调用,包括构造函数。如果您需要调用带有参数的构造函数,这将比使用反射/激活器运行速度快 5 倍左右。
The compiler can use the dynamic keyword so that the dlr will construct a type, but it's designed to late bind the arguments of a constructor rather than the type to be constructed. The opensource framework ImpromptuInterface abstracts the dlr calls, including the constructor. If you need to call a constructor that has arguments this will run about 5 times faster than using reflection/Activator.
我不知道你的目标是什么......但你的意思是这样的吗
?
上面只是调用类型
"SomeUnknownType"
的默认(无参数)构造函数,并将结果实例分配给dynamic
。I don't know what your goal is... but do you mean something like
?
the above just calls the default (parameterless) constructor of the Type
"SomeUnknownType"
and assign the resulting instance to adynamic
.