对于一个小项目,我创建了一个用于创建插件的基本界面。该接口(interface)有一个返回 UserControl 的函数。但是,当调用此方法并将 UserControl 添加到面板时,面板中不会显示任何内容(即使设置了 .Show()
或 Visibility = true
)。我假设当 assembly.CreateInstance()
被调用时,这会创建类中任何对象的实例。
不是这样的吗?是否需要在所有 UserControl 上调用 CreateInstance()
才能以这种方式使用它们?
public interface IMyInterface
{
System.Windows.Forms.UserControl GetConfigurationControl();
}
dll中的实现类:
public class myClass: IMyInterface
{
return new myUserControl();
}
加载目录中的所有dll:
private void LoadPlugins()
{
foreach (string file in Directory.GetFiles(Application.StartupPath+"/plugins/", "*.dll", SearchOption.AllDirectories))
{
Assembly assembly = Assembly.LoadFile(file);
var types = from t in assembly.GetTypes()
where t.IsClass &&
(t.GetInterface(typeof(IMyInterface).Name) != null)
select t;
foreach (Type t in types)
{
IMyInterface plugin = (IMyInterface)assembly.CreateInstance(t.FullName, true);
this.pluginsList.Add(plugin); //just a list of the plugins
}
}
this.AddPluginUserControls();
}
将用户控件添加到面板:
private AddPluginUserControls()
{
foreach (IMyInterface plugin in pluginsList)
{
myPanel.Controls.Add(plugin.GetConfigurationControl());
}
}
我知道其他完整的插件架构,但这更像是一个学习应用程序。 谢谢!
用户控件:
public partial class myUserControl: UserControl
{
public myUserControl()
{
InitializeComponent(); // couple of labels, vs generated.
}
}
最佳答案
确保两件事
1. 在默认的 myUserControl
构造函数中,InitializeComponent() 被调用,它将实例化并将您的标签添加到控件中。
2. 在添加到面板之前给用户控件一些宽度和高度。
关于c# - 动态加载的dll接口(interface)函数返回usercontrol,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16648318/