c# - 动态加载的dll接口(interface)函数返回usercontrol

标签 c#

对于一个小项目,我创建了一个用于创建插件的基本界面。该接口(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/

相关文章:

c# - 从 SQL Server 中转换一个 tiny int

c# - CSV 文件有不同的行

c# - 将 JSON 数据添加到通用集合

C# LINQ 选择具有相同属性值的对象加入其他属性值

c# - 通过数据注释进行身份验证和授权

c# - 从 .NET 中的 t 分数计算百分位数

C# - 如何从带有进度条的表单中取消后台工作?

c# - Crystal 报表公式: How to make value of a Numeric field to be empty if its value is zero?

c# - 是否可以将 unicode hex\u0092 显示(转换?)为 .NET 中的 unicode html 实体?

c# - WPF 数据网格 : DataGridComboxBox ItemsSource Binding to a Collection of Collections