我可以在运行时加载 .NET 程序集并实例化一个只知道名称的类型吗? [英] Can I load a .NET assembly at runtime and instantiate a type knowing only the name?

查看:33
本文介绍了我可以在运行时加载 .NET 程序集并实例化一个只知道名称的类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我只有 DLL 名称和类名,而不在项目中添加对程序集的引用,是否可以在运行时实例化对象?这个类实现了一个接口,所以一旦我实例化了这个类,我就会将它转换为接口.

Is it possible to instantiate an object at runtime if I only have the DLL name and the class name, without adding a reference to the assembly in the project? The class implements a interface, so once I instantiate the class, I will then cast it to the interface.

程序集名称:

library.dll

library.dll

类型名称:

公司.项目.类名

<小时>

我没有 DLL 的绝对路径,所以 Assembly.LoadFile 将不起作用.DLL 可能位于应用程序根目录、system32 中,甚至可能已加载到 GAC 中.


I dont have the absolute path of the DLL, so Assembly.LoadFile won't work. The DLL might be in the application root, system32, or even loaded in the GAC.

推荐答案

是的.您需要使用 Assembly.LoadFrom 将程序集加载到内存中,然后您可以使用 Activator.CreateInstance 以创建您首选类型的实例.您需要先使用反射查找类型.这是一个简单的例子:

Yes. You need to use Assembly.LoadFrom to load the assembly into memory, then you can use Activator.CreateInstance to create an instance of your preferred type. You'll need to look the type up first using reflection. Here is a simple example:

Assembly assembly = Assembly.LoadFrom("MyNice.dll");

Type type = assembly.GetType("MyType");

object instanceOfMyType = Activator.CreateInstance(type);

更新

当您有程序集文件名和类型名时,您可以使用Activator.CreateInstance(assemblyName, typeName) 要求 .NET 类型解析将其解析为类型.您可以使用 try/catch 对其进行包装,以便在失败时执行目录搜索,您可以在其中专门存储其他程序集,否则可能无法搜索到这些程序集.此时将使用前面的方法.

Update

When you have the assembly file name and the type name, you can use Activator.CreateInstance(assemblyName, typeName) to ask the .NET type resolution to resolve that into a type. You could wrap that with a try/catch so that if it fails, you can perform a search of directories where you may specifically store additional assemblies that otherwise might not be searched. This would use the preceding method at that point.

这篇关于我可以在运行时加载 .NET 程序集并实例化一个只知道名称的类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆