在C#中使用字符串调用UserControl [英] Call UserControl using string at C#

查看:128
本文介绍了在C#中使用字符串调用UserControl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,有没有人有一个很好的例子说明如何通过字符串调用许多UserControl之一:
我有很多课,如:

Hello, does anybody have a good example how to call one of many UserControls by a string:
I have many classes like:

public partial class UserControl1 : UserControl
public partial class UserControl2 : UserControl
public partial class UserControl3 : UserControl


和主要形式,以及一个字符串:


and main Form, and a string:

public partial class MainForm : Form
string[] callUserControl = {UserControl1,UserControl2,UserControl3};



在特定情况下,我想从字符串[X]调用UserControlX,然后将该控件传递给面板.
这些是用户控件类的名称,我想将控件的类型传递给面板,但要从字符串中选择它.
像反思



In specific event, I would like to call a UserControlX from a string[X], and pass that control to a panel.
Those are names of user control classes, and i want to pass the type of a control to the panel but by selecting it from a string.
Something like a Reflection

Thanks in advance!

推荐答案

例如,您可以使用Dictionary给出字符串中所需的类型,然后实例化该类型:

For example, you can use a Dictionary that gives the type you want from the string, and then instanciate the type:

//associates a type to a string
Dictionary<string, Type> types = new Dictionary<string, Type>();
//add your types
types["UserControl1"] = typeof(UserControl1);
types["UserControl2"] = typeof(UserControl2);
types["UserControl3"] = typeof(UserControl3);



要从字符串实例化类型:



To instanciate the type from the string:

UserControl InstanciateMyUserControl(string className)
{
    return types[className].InvokeMember(null, System.Reflection.BindingFlags.CreateInstance, null, null, null) as UserControl;
}


您是说要将控件的类型传递给面板,还是在谈论其中一个用户控件的实例?我之所以这样问是因为数组初始化器中的名称看起来像用户控件类的名称.

问候
Do you mean you want to pass the type of a control to the panel or are you talking about an instance of one of your user controls? I''m asking this because your the names in the array intializer look like the names of your user control classes.

Regards,


这篇关于在C#中使用字符串调用UserControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆