把大多数变量放在一个窗体的类级别是不是不好?这些会被认为是全局变量吗?
public partial class Form1 : Form
{
private string mode;
private int x, y;
public Form1()
{
InitializeComponent();
}
}
在类级别声明变量时,我在多个控件中使用这些变量。
最佳答案
这些将被视为类级全局变量(以区别于应用程序全局变量)。在本例中,更重要的区别是它们对类是private
的。
类级别的globals有它们的用途,所以我绝对不会说它是一个糟糕的实践。私有类全局变量的一个非常好的用途是,当您计划通过property accessors公开它们时。例如:public readonly
其值由类内部逻辑控制的属性。public
同时具有set
和get
访问器的属性(在setter中启用自定义验证逻辑。)
不过,我想说的是,除非另有必要,否则把事情搞得地方化是一个很好的做法。原因是,属于类实例的可变状态较少,因此出现此类错误的可能性较小:
private int EvilMethod1() {
x = (int) Math.Pow((double) y, 2);
return x;
}
private int EvilMethod2() {
y = (x + y) * 2;
return y;
}
// Assignments depend on the current values of x and y,
// as well as yielding unexpected side effects.
private void PureEvil()
{
// Return value depends on current y; has side effect on x while assigning y.
y = EvilMethod1();
// Return value depends on current x and y; has side effect on y while assigning x.
x = EvilMethod2();
}