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

查看:112
本文介绍了我可以在运行时加载.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

型号名称:

Company.Project.Classname

Company.Project.Classname

编辑:我没有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.

推荐答案

是的。你需要使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.reflection.assembly.loadfrom.aspx\"><$c$c>Assembly.LoadFrom该程序集加载到内存中,那么你可以使用<一个href=\"http://msdn.microsoft.com/en-us/library/d133hta4.aspx\"><$c$c>Activator.CreateInstance创建preferred类型的实例。你需要先了解一下类型了使用反射。下面是一个简单的例子:

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);

更新

当你的程序集文件名和类型名,你可以使用<一个href=\"http://msdn.microsoft.com/en-us/library/d133hta4.aspx\"><$c$c>Activator.CreateInstance(assemblyName,的typeName) 问.NET类型解析解析为一个类型。你可以换,与一个try / catch这样,如果它失败了,你可以执行搜索目录,在这里你可以具体存储,否则可能不被搜索附加组件。这将使用preceding方法,在这一点上。

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天全站免登陆