我意识到这已被部分涵盖,但我相信我所遇到的问题尚未完全涵盖:
我有一个事件在事件发生时创建Form
的对象:
private void hostView_AfterSelect(object sender, TreeViewEventArgs e)
{
string selectedNodeText = e.Node.Text;
if (selectedNodeText == "Internal Hosts" || selectedNodeText == "External Hosts")
{
// ignore, parent nodes have no corrosponding tab!
}
else
{
Form1 Form1Object = new Form1(selectedNodeText);
Form1Object.Show();
}
}
虽然我需要创建Form1
的许多对象,具体取决于"selectedNodeText"
字符串值。
例如:如果"selectedNodeText"
为== "Cars"
,我希望将Form1
的对象名称称为"Form1ObjectCars"
,如果它是"Dogs"
对象名称为"Form1ObjectDogs"
。
答案 0 :(得分:0)
您可以使用Dictionary<TKey,TValue>
类,例如
//Initialize
Dictionary<string, Form1> forms = new Dictionary<string, Form1>();
//Add objects
if(selectedNodeText == "foo")
forms.Add("foo", new Form1("foo"));
if(selectedNodeText == "bar")
forms.Add("bar", new Form1("bar"));
//Get objects
Form1 bar = forms["bar"];
答案 1 :(得分:0)
听起来你正在使用相同的表单,但只想标题或标题不同。
string caption = string.Format("Form1Object{0}", selectedNodeText);
Form1 Form1Object = new Form1(caption);
// in the Form's constructor you are doing a this.Text = caption?
Form1Object.Show();
或者为了避免将其传递给表单:
Form1 Form1Object = new Form1();
Form1Object.Text = string.Format("Form1Object{0}", selectedNodeText);
Form1Object.Show();