我试图学习如何将 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!");
}
}
}
在我的主程序中,我尝试做这样的事情:
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 != null)
{
Action new_action = myDll.CreateInstance(type.FullName) as Action;
if (new_action != null)
actions.Add(new_action);
else
Console.WriteLine("New Action is NULL");
}
}
foreach (Action action in actions)
action.DoAction();
}
我遇到的问题是,即使
type.FullName
包含正确的值(“TestDLL.PrintString”等),
线
myDll.CreateInstance(type.FullName) as Action
总是返回 null。
我不完全确定问题是什么,或者我如何解决它。
如示例所示,我希望能够将新的 Action 实现添加到 DLL,并让主程序在每个实现上调用 DoAction(),而无需重新编译原始程序。希望这是有道理的!