C#-从.NET DLL(类库)执行代码而不引用它? [英] C# - Execute code from a .NET DLL (Class Library) without referencing it?

查看:126
本文介绍了C#-从.NET DLL(类库)执行代码而不引用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种方法,可以在启动应用程序后从.NET DLL执行代码。我在下面添加了一些伪代码,这些伪代码可能会尝试解释我的尝试。我知道它可能比我看上去的要复杂得多。

I am trying to find a way in which I can execute code from a .NET DLL after my application has already been launched. I have included some pseudo-code below that might try and explain what I'm trying to do. I know it's probably a lot more complicated than I make it seem.

ClassLibrary myLibrary = new ClassLibrary("C:\\Users\\Admin\\Desktop\\myTestLibrary.dll");
myLibrary.executeMethod("showMessageMethod", arg1, arg2, arg3...);

这是我想做的,尽管我知道它可能要复杂得多!

That's what I want to do although I understand it's likely far more complicated than that!

我也想明确表示我理解您是要引用项目中的库等,但是我的项目需要

I would also like to make it clear that I do understand that you're meant to reference the library in your project etc... but my project requires that I don't do it this way.

谢谢!

推荐答案

您需要从磁盘加载程序集,如下所示:

You'll need to load the assembly from disk, as follows:

Assembly myLibrary = System.Reflection.Assembly
    .LoadFile("C:\\Users\\Admin\\Desktop\\myTestLibrary.dll");

之后,您将需要使用反射获取正确的类型并调用正确的方法。当您要调用的类实现在启动时引用的程序集中定义的接口时,将最方便:

After that you will need to get the proper type using reflection and invoke the proper method. It will be most convenient when that class you want to call implements an interface that is defined in an assembly that is referenced at startup:

Type myClass = (
    from type in myLibrary.GetExportedTypes()
    where typeof(IMyInterface).IsAssignableFrom(type)
    select type)
    .Single();

var instance = (IMyInterface)Activator.CreateInstance(myClass);

instance.executeMethod("showMessageMethod", arg1, arg2, arg3...);

这篇关于C#-从.NET DLL(类库)执行代码而不引用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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