Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在c#应用程序中动态添加自定义控件_C#_Dll - Fatal编程技术网

在c#应用程序中动态添加自定义控件

在c#应用程序中动态添加自定义控件,c#,dll,C#,Dll,我创建了两个自定义控件。根据特征,将选择其中任何一个并在C#应用程序中使用。我已经加载了所需的控件,但如何使用这些函数,例如,我的控件LoadXML()有一个公共函数。两个控件都包含此函数。 一次只能加载一个控件。创建控件的实例,然后将其添加到表单中,然后可以调用其公共公开方法 TestControl myTestControl = new TestControl(); this.Controls.Add(myTestControl); myTestControl.LoadXML();

我创建了两个自定义控件。根据特征,将选择其中任何一个并在C#应用程序中使用。我已经加载了所需的控件,但如何使用这些函数,例如,我的控件LoadXML()有一个公共函数。两个控件都包含此函数。
一次只能加载一个控件。

创建控件的实例,然后将其添加到表单中,然后可以调用其公共公开方法

 TestControl myTestControl = new TestControl();
 this.Controls.Add(myTestControl);
 myTestControl.LoadXML();
如果您是通过dll加载控件,请尝试以下方法调用该方法:

    // Use the file name to load the assembly into the current
    // application domain.
    Assembly a = Assembly.Load("example");
    // Get the type to use.
    Type myType = a.GetType("Example");
    // Get the method to call.
    MethodInfo myMethod = myType.GetMethod("MethodA");
    // Create an instance.
    object obj = Activator.CreateInstance(myType);
    // Execute the method.
    myMethod.Invoke(obj, null);

如果我正确理解了您的问题,您应该创建一个接口,并向其中添加函数
LoadXML()
。在自定义控件上实现该接口。现在,您可以创建接口的对象,并使用所需的控件对其进行初始化

interface MyInterface
    {
        void LoadXML();
    }
在用户控件中,实现
MyInterface

public class UserControl1 : UserControl, MyInterface
    {
        public void LoadXML()
        {
          ...  //do what you want
        }
    }
同样适用于
UserControl2
现在在接口对象中加载所需的用户控件,并调用
LoadXML()


希望它能有所帮助。

如何加载它们?你知道它们装在哪里吗?何时必须调用LoadXML()?myassembly=Assembly.LoadFrom(Application.StartupPath+“\\PDF”+“\\x86”+“\\PDFView”+“.dll”);}if(myassembly!=null){Type t=myassembly.GetType(“PDFView.PDFViewer”);cc=(Control)Activator.CreateInstance(t);this.Controls.Add(cc);cc.Dock=DockStyle.Bottom;cc.Show();我正在从两个控件的.dll加载。应用程序将在运行时决定加载哪个.dll。cc=(控件)Activator.CreateInstance(t);此处强制转换为您的特定控件类型,而不是控件我已强制转换为其他类型,但在我的应用程序中仍然无法访问这些方法。如果我调用它们,则会出现编译时错误://使用文件名将程序集加载到当前//应用程序域。程序集a=assembly.load(“示例”);//获取要使用的类型。类型myType=a.GetType(“示例”);//获取要调用的方法。MethodInfo myMethod=myType.GetMethod(“MethodA”);//创建实例。对象obj=Activator.CreateInstance(myType);//执行方法。myMethod.Invoke(obj,null);//检查此链接
 class Class
    {
        MyInterface control;

        public Class()
        {
            if (condition == true)
                control = new UserControl1();
            else
                control = new UserControl2();

            control.LoadXML();
        }
    }