如何从类型名称和程序集名称加载类型
我需要获取一个类型的实例,我将在运行时获得其名称和程序集名称。我事先知道该类型将有一个无参数构造函数。做到这一点最简单的方法是什么?
这比我希望的要难得多。
编辑:我不知道这是否相关,但程序集将被引用。我不需要从磁盘或其他东西加载它。
I need to get an instance of a type whose name and assembly name I will have at runtime. I know in advance the type will have a parameterless constructor. What's the easiest way to do this?
It's waaaaaaay harder than I was hoping it would be.
Edit: I'm not if this is relevant, but the assembly will be referenced. I don't need to load it from disk or something.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx
http://msdn.microsoft.com/en-us/library /system.type. assemblyqualifiedname.aspx
http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx
http://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname.aspx
来自 MSDN:
示例:
From MSDN:
Example:
如果引用 System.Web.dll 对您来说不是问题,那么还有一个鲜为人知的 BuildManager.GetType Method 非常高效。它甚至不需要程序集名称,因为它会扫描当前 AppDomain 执行路径中程序集中的类型。
所以代码是:
If referencing System.Web.dll is not an issue for you, there is the little-known BuildManager.GetType Method which is quite efficient. It does not even requires the assembly name because it scans for types in assemblies in the current AppDomain execution path.
So the code would be:
以下应该足够了:
The following should suffice:
激活器
类型
Activator
Type
这是使用花哨的
dynamic
关键字来工作的东西。您需要引用其他类才能通过测试,或者使用构建事件来复制构建的 DLL。与 Activator 不同,AppDomain.CurrentDomain.CreateInstanceFromAndUnwrap 接受文件名作为第一个参数,而不是类型说明符。这有时很有用,特别是当您不关心程序集的强名称时。
Here's something that works using the fancy
dynamic
keyword. You'll need to reference the other class for the test to pass, or use a build event to copy over the built DLL.Unlike
Activator
,AppDomain.CurrentDomain.CreateInstanceFromAndUnwrap
takes a filename as the first argument rather than a type specifier. This is sometimes useful, especially when you don't care about the strong name of the assembly.