我想添加一个按钮,使用一个接受一行中所有参数的函数来保持它的清洁。但是,如果我尝试通过This.Controls.Add
添加按钮,则会出现错误,因为该函数是静态的。我应该写什么而不是This
(像Form1.Controls.Add
这样的东西)所以我可以在一个函数中做所有事情?
答案 0 :(得分:2)
您可以将表单作为静态函数的参数:
public static void CreateButton(Form targetForm, param1, param2, ...) {
Button b = new Button();
...
targetForm.Controls.Add(b);
}
...但除非使用此方法将按钮添加到各种表单中,否则我不会看到像这样使其静态化的优势。这似乎是一种OO反模式。我可能会将其设为非静态并使用this
。
答案 1 :(得分:0)
我只需要你的功能返回按钮:
//Usage
this.Controls.Add(CreateButton(...));
//Function def
public static Button CreateButton(...)
{
Button createdButton = new Button();
...
return createdButton;
}
分配返回分配的结果(因此您可以链接它们)。所以内联作业:
//With a variable (I did *not* say it was good practice to do this)
this.Controls.Add(myVar = CreateButton(...));