使用许多全局变量的编程是否正确?

本文关键字:是否 编程 许多 全局变量 | 更新日期: 2023-09-27 18:14:22

在我的应用程序中,我注意到我有大约30个全局变量。它是糟糕的编程和更好的方式是传递给变量使用函数或它并不重要?

这是public partial class MainWin : Form

中所有全局变量的列表
private const int WM_SYSCOMMAND = 0x112;
private const int SC_CONTEXTHELP = 0xf180;
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
NetworkAdapter selectedAdapter = null;
string lastPath = "";
int _selectedIndex;
bool bContinuePlay;
bool ifContinue = true;
decimal delay = 10;
int delayBetweenLoops;
ManualResetEvent manualResetEvent = new ManualResetEvent(false);
BackgroundWorker backGroundWorker = null;
bool isBurst = true;
IpV4Address oldIpAddress;
IpV4Address newIpAddress;
ushort oldPort;
ushort newPort;
MacAddress oldMacAddress;
MacAddress newMacAddress;
bool fixBadChecksum = false;
bool removePPPOE = false;
bool removeVlan = false;
bool fragmentation = false;
private DateTime lastCheck = DateTime.MinValue;
bool continuePlay = true;
RangeFinder range = null;
IpV4Address oldRangeIp;
IPAddress newRangeIpStart;
int loopsCount;
decimal numberOfLoops;
double playSpeed;
string path = "";
bool isError = false;

使用许多全局变量的编程是否正确?

将变量移动到使用它们的类中。你不是在告诉我bContinuePlayoldIpAddresspath之间有什么关系。

这取决于程序。如果你所有的代码都是一个main函数,为什么不呢?如果它是一个庞大的系统,当然不是一个好的设计,因为它以后会变得混乱。

可能值得一读:http://c2.com/cgi/wiki?GlobalVariablesAreBad

全局变量只有在程序的许多函数中需要它时才有用,传递它会使参数列表太长。

使用全局变量作为一次性变量是不好的做法。

是。尽量避免全球化,他们是不好的。您可以使用实用程序类的静态成员,或传递输入和输出参数,或类成员。

例如Java没有独立的参数,一切都是一个类或属于你的例子,我会创建一个类持有所有的配置。

比如

类GameConfiguration也许可以添加静态方法(如果你没有多线程)..