-1

在我的应用程序中,我注意到我有大约 30 个全局变量。它是糟糕的编程和击球方式是使用函数传递给变量还是没关系?

这是我所有 globat 变量的列表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;
4

4 回答 4

4

将变量移动到使用它们的类中。你不是告诉我那个bContinuePlay, oldIpAddress, 和path彼此有任何关系。

于 2013-05-20T16:51:17.680 回答
1

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

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

于 2013-05-20T16:49:16.570 回答
0

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

但是,将全局变量用作一次性变量是一种不好的做法。

于 2013-05-20T16:52:28.950 回答
-1

是的。尽量避免全局,它们是没有好处的。您可以使用实用程序类的静态成员,或传递输入和输出参数,或类成员。

例如,Java 没有独立参数,一切都是类或属于您的示例我将创建一个包含所有配置的类。

就像是

类 GameConfiguration 并可能向其添加静态方法(如果您没有多线程)..

于 2013-05-20T16:48:34.297 回答