我的combobox里有很多item,想点某一item的时候就根据item的信息来new个窗体。比如如果是"绘制点",我就new个负责绘制点的窗体并显示现在问题是item很多,如果if来判断并new的话代码好像很冗余。请问如何组织?如果用根据item的名字起类名并反射的话似乎效率也不高。。有什么代码如何组织的建议吗?

解决方案 »

  1.   

    你可以把类的全称记录到Item里,使用Type.GetType来得到 这个类型并建立实例运行.
      

  2.   

    楼主发了两个帖子啊.
    我写了一个例子,你看一下吧:
    public partial class Form1 : Form
    {
    class cboItem
    {
    private string m_Text;
    private string m_fullName;
    public cboItem(string text, string fullName)
    {
    this.m_Text = text;
    this.m_fullName = fullName;
    }
    public override string ToString()
    {
    return this.m_Text;
    }
    public string Text
    {
    get
    {
    return this.m_Text;
    }
    }
    public string FullName
    {
    get
    {
    return this.m_fullName;
    }
    }
    }
    public Form1()
    {
    InitializeComponent();
    cboItem item = new cboItem("窗体", typeof(Form1).FullName);
    this.comboBox1.Items.Add(item);
    } private void button1_Click(object sender, EventArgs e)
    {
    if (this.comboBox1.SelectedIndex != -1)
    {
    cboItem item = this.comboBox1.SelectedItem as cboItem;
    if (item != null)
    {
    object obj = Activator.CreateInstance(Type.GetType(item.FullName));
    Form f = obj as Form;
    if (f != null)
    {
    f.Show();
    }
    }
    }
    }
    }