日期:2014-05-19  浏览次数:20746 次

一个小问题,解决就给分
我的combobox里有很多item,想点某一item的时候就根据item的信息来new个窗体。比如如果是 "绘制点 ",我就new个负责绘制点的窗体并显示

现在问题是item很多,如果if来判断并new的话代码好像很冗余。请问如何组织?如果用根据item的名字起类名并反射的话似乎效率也不高。。

有什么代码如何组织的建议吗?

------解决方案--------------------
多判断的话

switch(参数)
{
case 1 :
//...
break;
case 2 :
//...
break;
//....
default :
//...
break
}
------解决方案--------------------
--似乎效率也不高

这种效率的损失可以忽略不计的
------解决方案--------------------
给你个例子参考下:
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();
}
}
}
}
}