c# - 从 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)
有可能吗?
解决方案
您可以使用回调。
您在 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
委托。
推荐阅读
- scala - 如何在Scala中检查Option是否为None
- r - r markdown 中的内联代码按“原样”打印
- javascript - 动态按钮 ID - Javascript
- java - 使用 Java (1.8) 使用 RSCRLF 而不仅仅是使用 CRLF 打破一条线
- css - 有 span 标签 innerHTML 不是换行符
- mysql - 测试中的命令导致测试无法完全退出
- java - jackson-dataformat-csv:没有 POJO 的映射数字值
- python - 如何在 python 上绘制 8 位图像的 16,32 和 64 bin 直方图?
- python - 如何在不等待python的情况下执行linux脚本并返回http post响应
- javascript - 在 Textarea 中按 ID 搜索元素并替换它