所以,我有一个名为CreateWindow的函数(字符串id,int width,int height,string title);
正如您可能已经猜到的那样,此函数会在调用时创建一个窗口并添加参数。我打算这样做:public static void CreateWindow(string id,int width,int height,string title) {
Form (value of id) = new Form();
(value of id).Text = title;
(value of id).Size = new Size(width,height);
Main(Form (value of id));
}
但是,我需要使表单的标识符等于变量' id'或者我无法完成任何工作,我无法用例如(value of id)
替换form1
,因为如果用户想要更改窗口的另一个属性,他应该能够简单地做到,例如:(value of id).BackColor = Color.Green;
答案 0 :(得分:2)
我已经添加了一个完整的程序供您在下面尝试,没有任何错误处理以保持简短。只需创建一个新的Windows应用程序并粘贴代码即可。
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace CreateFormWindowSO
{
static class Program
{
[STAThread]
static void Main()
{
var windowId = "Some window";
CreateWindow(windowId, 320, 240, "My Window");
// Put a breakpoint on the line below and step over it with the debugger.
// You'll see it returns the correct form object that was created above.
var someWindow = GetWindow(windowId);
// Do something with 'someWindow'.
}
static Form GetWindow(string id)
{
return windows[id];
}
static void CreateWindow(string id, int width, int height, string title)
{
Form form = new Form();
form.Text = title;
form.Size = new Size(width, height);
windows.Add(id, form);
}
static Dictionary<string, Form> windows = new Dictionary<string, Form>();
}
}
字典背后的想法是,您现在能够将Form
与特定的“密钥”关联(在这种情况下为id
)。这使您可以通过向GetWindow()
提供您可能在其他地方跟踪的密钥来查找特定窗口。您现在可以单独创建窗口,并在以后需要时随时获取它们。
答案 1 :(得分:1)
我认为动态变量命名是不可能的。您可以使用public static Dictionary<string, Form> forms;
等表单的静态字典,并使用索引的ID将新表单添加到集合中。
public static Dictionary<string, Form> forms = new Dictionary<string, Form>();
public static Form CreateWindow(string id, int width, int height, string title)
{
if (!forms.ContainsKey(id))
forms.Add(id, new Form());
forms[id].Text = title;
forms[id].Width = width;
forms[id].Height = height;
return forms[id];
}