C#create DLL插件实现接口

Ent*_*ity 4 c# dll load

我正在编写一个简单的基于插件的程序.我有一个接口IPlugin,它有一些方法和功能,并List<Plugin>在我的主程序中.为简单起见,我们说它的定义如下:

public interface IPlugin
{
    public void OnKeyPressed(char key);
}
Run Code Online (Sandbox Code Playgroud)

每次按下一个键,我都会遍历插件列表,然后调用OnKeyPressed(c)每个键.

我可以像这样创建一个类,并将其添加到列表中......

public class PrintPlugin
{
    public void OnKeyPressed(char key)
    {
        Console.WriteLine(c);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后每当你按一个键,它就会打印出来.但我希望能够从DLL文件加载插件.这个链接很有帮助,但它没有解释如何让DLL中的类实现我的IPlugin界面......我怎么能这样做?我真的不想IPlugin.cs每次想要制作插件时都要复制文件...

dee*_*ee1 6

如果我正确地理解你......

创建3个项目:

项目1:您的主程序(包含List的程序)

项目2:带有您的界面的项目

public interface IPlugin
{
public void OnKeyPressed(char key);
}
Run Code Online (Sandbox Code Playgroud)

项目3:示例插件

public class PrintPlugin : IPlugin
{
public void OnKeyPressed(char key)
{
    Console.WriteLine(c);
}
}
Run Code Online (Sandbox Code Playgroud)

然后添加项目2作为项目1和3的参考.

这样您就可以与主项目和任何插件共享界面.

我在几个项目中使用了这个,它对我很有帮助.