在运行时动态更改对 dll 的引用 [英] Dynamically change the reference to a dll at runtime

查看:26
本文介绍了在运行时动态更改对 dll 的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的情况是,我在不同的文件夹中有多个 .dll 文件,它们都具有相同的名称,包含相同的函数(名称相同),但同名函数内部的代码不同.

I have a situation where I have several .dll files in different folders , all with the same name , that contains the same functions ( with the same names ) , but the code inside functions with the same name is different.

我在设计中创建了我的应用程序,引用了这些 .dll 文件之一.但我希望在我的应用程序启动时,使用选择案例能够更改对这些 dll 之一的引用.

I have created my application in design , referencing one of these .dll files. But I want that when my application start , using a select case to be able to change the reference to one of these dll.

这可能吗?

谢谢!

推荐答案

你不能那样做,如果你想使用你在运行时选择的 dll,你需要从不在你的项目中直接引用它开始(不能在运行时更改)然后使用 Assembly.Load 手动将它加载到您的应用程序域中并对其进行反映以使用它的类型(因为您在编译时不知道类型,因为它没有被引用,所以您必须编程它针对您查询的类型).

You can't do that, if you want to use a dll that you select at runtime, you need to start by NOT referencing it directly in your project (that can't be changed at runtime) then manually loading it in your appdomain using Assembly.Load and reflect upon it to use it's types (as you don't know the types at compile time as it's not referenced, so you have to program it against types you query).

因此,如果您已经针对引用的 dll 进行了编程,那么您就做错了,因为如果您需要它是动态的,那么在其中使用代码的整个方式是不同的.

So if you already programmed against the referenced dll, you did it wrong, as the whole way of using the code Inside it is diferent if you need it to be dynamic.

例如,如果您在名为mydll.dll"的 dll 中有一个类型mytype"和一个方法mymethod",如果您使用它来引用它就像这样做一样简单

For example if you have a type "mytype" with a method "mymethod" in a dll named "mydll.dll" if you reference it using it is as simple as doing

new mytype().mymethod();

如果你不是引用 dll 而是动态解析它,它看起来像

If you're not referencing the dll but resolving it dynamically it would look like

var asm = Assembly.Load("mydll.dll");
var type = asm.DefinedTypes.Single(t=>t.Name == "mytype");
var instance = Activator.CreateInstance(type);
var methodinfo = type.GetMethod("mymethod");
methodinfo.Invoke(instance);

此外,我们需要知道您要实现的目标,有一些方法可以使这更简单,但这取决于您的用例(例如,在插件系统中,您会为插件声明一个接口并共享该dll并直接引用它,仅动态加载插件,因此您可以直接将实例转换为该接口而不必动态调用方法)

Also we need to know what you're trying to achieve, there are ways to make this a bit simpler but it depends on your use case (in a plugin system for example you'd declare an interface for the plugin and share that dll and reference it directly, only loading the plugins dynamically, so you could directly cast instance to that interface and not have to invoke methods dynamically)

这篇关于在运行时动态更改对 dll 的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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