我正在尝试学习如何将DLL动态加载到C#程序中。这个想法是DLL将包含一个接口和该接口的几个不同实现,因此,如果我想添加新的实现,则不必重新编译整个项目。
所以我创建了这个测试。这是我的DLL文件:
namespace TestDLL
{
public interface Action
{
void DoAction();
}
public class PrintString : Action
{
public void DoAction()
{
Console.WriteLine("Hello World!");
}
}
public class PrintInt : Action
{
public void DoAction()
{
Console.WriteLine("Hello 1!");
}
}
}
Run Code Online (Sandbox Code Playgroud)
在我的主程序中,我尝试执行以下操作:
static void Main(string[] args)
{
List<Action> actions = new List<Action>();
Assembly myDll = Assembly.LoadFrom("TestDLL.dll");
Type[] types = myDll.GetExportedTypes();
for (int i = 0; i < types.Length; i++)
{
Type type = types[i];
if (type.GetInterface("TestDLL.Action") != null && type …Run Code Online (Sandbox Code Playgroud)