读书人

传进去是什么就创建什么,如何写呢? 帮

发布时间: 2013-01-23 10:44:50 作者: rapoo

传进去是什么就创建什么,怎么写呢? 帮帮我吧,好像跟泛型有关
class Class1: Control
{
//private Button btn;
//private Type ItemClass;

public void CreateItems<T>(int count, ref T ItemClass)
{

//Button<t> = new Button<t>();
//Type tp = Type.GetType(classname);


Button item = new Button();
item.Left = x;
item.Top = y;
item.Width = 65;
item.Height = 65;
item.Click += new EventHandler(Item_Click);
this.Controls.Add(item);


}
}


private void button1_Click(object sender, EventArgs e)
{
Class1 aa = new Class1();
aa.Left = 0;
aa.Top = 0;
aa.Width = 200;
aa.Height = 200;
this.Controls.Add(aa);
//aa.CreateItems(10, ButtonClass);
aa.CreateItems<Button>(10, typeof(Button));

}


有个类class1, 它有个方法createitems, 我希望传进去是button类的,就创建出button类,如果传进去是Panel类的,就创建出Panel类. 传进去的类不只这两种,可以有很多. class1不知道.
可以教教我怎么写吗? 最好是可以运行的代码.
[解决办法]


public void CreateItems<T>(int count) where T : Control,new()
{
int x, y;
x = 0;
y = 0;
for (int i = 0; i < count; i++)
{


T item = new T();
item.Left = x;
item.Top = y;
item.Width = 65;
item.Height = 65;
item.Text = i.ToString();
item.Click += new EventHandler(Item_Click);
this.Controls.Add(item);
}
}


[解决办法]
class Class1 : Control
{
private Dictionary<string, Control> Controls = new Dictionary<string, Control>();
public void CreateItems<T>(int count) where T : Control, new()
{
string str = Regex.Match(typeof(T).ToString(), @"(?<=\.)\w+$").Value;
int n = 0;
for (int i = 0; n < count; i++)
{
if (!Controls.ContainsKey(str + i) )
{
T item = new T();
item.Text = str + i;
Controls.Add(str + i, item);
n++;
}

}
}
public Control this[string key]
{
get { return Controls[key]; }
}
}
传进去是什么就创建什么,如何写呢? 帮帮小弟我吧,好像跟泛型有关

读书人网 >C#

热点推荐