【发布时间】:2016-02-16 02:23:31
【问题描述】:
我必须为数组的成员(我不知道这是否正确)赋值。我将我的数组成员定义如下:(所有这些代码都在公共类 BWClass 中)
public static BackgroundWorker[] bwCA = new BackgroundWorker[25];
public static int NumbwCA;
private static bool HasRunOnce = false;
public static void BackgroundWorkerInitializer(bool doFirst, int numbwCA)
{
// Okay we got here. So we can presume that array checking (number not exceeding the array) is already done
if (!HasRunOnce)
{
NumbwCA = numbwCA; // for access
} // Now it is impossible to stop less backgroundworkers then started later on in the code
if (doFirst)
{
for (int i = 0; i < NumbwCA; i++)
{
string strpara = (numbwCA.ToString()); // Could also directly write numbwCA.ToString() directly in the RunWorkerAsync() method
bwCA = new BackgroundWorker[NumbwCA];
bwCA[i] = new BackgroundWorker();
bwCA[i].WorkerReportsProgress = true;
bwCA[i].WorkerSupportsCancellation = true;
bwCA[i].DoWork += new DoWorkEventHandler(bwa_DoWork);
bwCA[i].ProgressChanged += new ProgressChangedEventHandler(bwa_ProgressChanged);
bwCA[i].RunWorkerCompleted += new RunWorkerCompletedEventHandler(bwa_RunWorkerCompleted);
bwCA[i].RunWorkerAsync(strpara);
}
}
else // DoSecond
{
// stop the backgroundworkers
for (int i = 0; i < NumbwCA; i++)
{
if (bwCA[i].IsBusy == true)
{
bwCA[i].CancelAsync();
HasRunOnce = false; // If restarting the server is required. The user won't have to restart the progrem then
}
else
{
Console.WriteLine(">>The backgroundworkers are already finished and don't need canceling");
}
}
}
}
此代码在公共类中。 我认为当我在一个类中完成所有数组制作时,我将不再有变量范围的问题。但是我错了。当 bwCA[i].IsBusy == true 运行时,我仍然收到错误 nullReferenceException。也可能在 for 循环之外的任何内容运行时。
我知道我不能在循环外使用 bwCA[i] 如果它被声明,但我该如何更改它,以便我可以在代码中的其他地方访问 bwCA[i](如在"else // DoSecond)?
顺便说一句。我不喜欢使用列表
【问题讨论】:
标签: c# arrays loops scope nullreferenceexception