首页 > 解决方案 > 从 C# 中的 dll 调用程序中的方法

问题描述

我想从我的 dll 调用我的程序中的一个方法。
我现在可以添加一个论点public void Bar(Action<string> print, string a)。但是还有其他方法可以调用它吗?
dll中的代码:

class Foo {
    public void Bar(string a) {
        //now I want to call method from program
        Program.Print(a); // doesn't work
    }
}

程序:

class Program {
    public static void Main(string[] args) {
        var dll = Assembly.LoadFile(@"my dll");
        foreach(Type type in dll.GetExportedTypes())
        {
            dynamic c = Activator.CreateInstance(type);
            c.Bar(@"Hello");
        }
        Console.ReadLine();
    }
    public static void Print(string s) {
        Console.WriteLine(s);
    }
}

来自(在 C# 中运行时加载 DLL
有可能吗?

标签: c#dll

解决方案


您可以使用回调。

您在 dll 中添加一个事件。

从您分配事件的程序中。

因此,您可以从 dll 中调用事件。

在dll中放入一个公共类:

public event EventHandler MyCallback;

从程序将其设置为所需的方法:

MyDllClassInstance.MyCallback = TheMethod;

现在,您可以从 dll 类中编写:

if (MyCallback != null) MyCallback(sender, e);

您可以使用任何预定义的事件处理程序或创建您自己的事件处理程序。

例如对于您的 dll 代码:

public delegate PrintHandler(string s);

public event PrintHandler MyCallback;

public void Bar(string s)
{
  if (MyCallback != null) MyCallback(s);
}

所以在程序中你可以放:

class Program {
  public static void Main(string[] args) {
      var dll = Assembly.LoadFile(@"my dll");
      foreach(Type type in dll.GetExportedTypes())
      {
          dynamic c = Activator.CreateInstance(type);
          c.MyCallback = Print;
          c.Bar(@"Hello");
      }
      Console.ReadLine();
  }
  public static void Print(string s) {
      Console.WriteLine(s);
  }
}

您可以使用Action<string>而不是定义PrintHandler委托。


推荐阅读