【发布时间】:2014-12-17 18:54:56
【问题描述】:
我想添加一个按钮,使用一个函数将所有参数放在一行中,以保持它的整洁。但是如果我尝试通过This.Controls.Add 添加按钮,我会收到错误,因为该函数是静态的。我应该写什么而不是This(类似于Form1.Controls.Add),这样我就可以在一个函数中完成所有事情?
【问题讨论】:
-
如果你需要访问表单,为什么方法首先是静态的?
我想添加一个按钮,使用一个函数将所有参数放在一行中,以保持它的整洁。但是如果我尝试通过This.Controls.Add 添加按钮,我会收到错误,因为该函数是静态的。我应该写什么而不是This(类似于Form1.Controls.Add),这样我就可以在一个函数中完成所有事情?
【问题讨论】:
您可以将表单作为静态函数的参数:
public static void CreateButton(Form targetForm, param1, param2, ...) {
Button b = new Button();
...
targetForm.Controls.Add(b);
}
...但是除非这种方法将用于将按钮添加到各种表单中,否则我看不到将其设为静态的好处。这似乎是一种 OO 反模式。我可能会将其设为非静态并使用this。
【讨论】:
我只想让你的函数返回按钮:
//Usage
this.Controls.Add(CreateButton(...));
//Function def
public static Button CreateButton(...)
{
Button createdButton = new Button();
...
return createdButton;
}
Assignment 返回分配的结果(因此您可以将它们链接起来)。所以要内联分配:
//With a variable (I did *not* say it was good practice to do this)
this.Controls.Add(myVar = CreateButton(...));
【讨论】: