为未引用的 DLL C# 中的方法创建线程

Create Thread for Method in Unreferenced DLL C#

美好的一天,

我的目标是在 C# 中创建一个程序(windows 服务,atm 它只是一个控制台应用程序),它使用未被引用的 .dll 并为 .dll 中的方法创建线程 ' s.

换句话说:我想创建一个程序,为未知 .dll 的方法启动线程

例如,我有一个名为 testdll.dll 的 .dll,其中包含一个方法 cWrite() 在我的主程序中,我想为 cWrite() 创建一个线程,但是没有引用 .dll。

目前我的代码如下所示:

var assembly = Assembly.LoadFrom("testdll.dll");
var aClass = assembly.GetType("testdll.Class1");
dynamic instance = Activator.CreateInstance(aClass);

Thread t1 = new Thread(instance.cWrite());

我收到错误:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 无法在 CallSite.Target(Closure , CallSite , Object ) 在 System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site) 将类型 'void' 隐式转换为 'object' , T 0 arg0) at testService.Program.Main() in C:...\Program.cs:line 85

我知道有多种方法可以使用未引用的 dll,但我正在努力为其中一个 dll 中的方法创建线程。

感谢任何帮助,
问候
杰夫

您可以简单地:Thread t1 = new Thread(() => instance.cWrite()); 作为 Thread 构造函数需要委托来调用,同时您将 cWrite()(即 void)的结果传递给它。

为什么不使用 MEF?您可以设置 .dll 的搜索目录,然后将您想要的任何 .dll 放在那里。您唯一需要在代码中包含的是使用对象时的接口。

https://msdn.microsoft.com/en-us/library/dd460648(v=vs.110).aspx

导出和导入所需的示例通用接口:

interface IMyMEFExample
{
    public string HelloFromMEF();
}

导出示例Class:

[Export(typeof(IMyMEFExample))]
public class MyExportedMEFClass : IMyMEFExample
{
    public string HelloFromMEF()
    {
        return "Hello from MEF!";
    }
}

MEF 消耗示例:

class ImportMEFExample
{
    [Import(typeof(IMyMEFExample))]
    private IMyMEFExample importedMEF;

    public ImportMEFExample()
    {
        Console.WriteLine(importedMEF.HelloFromMEF());
    }
}