我最初有以下代码:
Boolean successCheckPoint = false;
Boolean failureCheckPoint = false;
Boolean timeFound = false;
foreach (var row in auditRows)
{
timeFound = row.Text.Contains(sCurrentTime) || row.Text.Contains(sLenientTime) || row.Text.Contains(sLenientTime2) ? true : false;
if (timeFound)
{
successCheckPoint = row.Text.Contains("Web User Login Success") && !successCheckPoint ? true : false;
failureCheckPoint = row.Text.Contains("Web User Login Failure") && !failureCheckPoint ? true : false;
}
}
但我发现,在 foreach 的后续迭代中,即使 successCheckPoint 或 failureCheckPoint 布尔值设置为 true,由于我设置分配的方式,它们最终也会设置为 false。
示例问题
第一次迭代
- timeFound 是真的
- 成功检查点为假
- row.Text 确实包含我想要的文本
- successCheckPoint 确实是假的
- 成功检查点设置为真
第二次迭代
- timeFound 是真的
- 成功检查点为真
- row.Text 不包含我想要的文本
- successCheckPoint 不为假
- 成功检查点设置为假
所以为了解决这个问题,我将代码更改为:
Boolean successCheckPoint = false;
Boolean failureCheckPoint = false;
Boolean timeFound = false;
foreach (var row in auditRows)
{
timeFound = row.Text.Contains(sCurrentTime) || row.Text.Contains(sLenientTime) || row.Text.Contains(sLenientTime2) ? true : false;
if (timeFound)
{
if (!successCheckPoint)
{
successCheckPoint = row.Text.Contains("Web User Login Success") ? true : false;
}
if (!failureCheckPoint)
{
failureCheckPoint = row.Text.Contains("Web User Login Failure") ? true : false;
}
}
}
这可以满足我的要求,但感觉应该有更好的方法来完成这种行为。有什么方法可以设置,一旦布尔值设置为真,它就不会在未来的迭代中变回假?
正确的行为
第一次迭代
- timeFound 是真的
- 成功检查点为假
- row.Text 确实包含我想要的文本
- successCheckPoint 确实是假的
- 成功检查点设置为真
第二次迭代
- timeFound 是真的
- successCheckPoint 为真,因此跳过重新评估
抱歉,如果这仍然令人困惑。如有必要,我可以多解释一点。
编辑:现在我考虑一下,我真的不需要'?此代码的 true : false' 部分。
新代码:
Boolean successCheckPoint = false;
Boolean failureCheckPoint = false;
Boolean timeFound = false;
foreach (var row in auditRows)
{
timeFound = row.Text.Contains(sCurrentTime) || row.Text.Contains(sLenientTime) || row.Text.Contains(sLenientTime2);
if (timeFound)
{
if (!successCheckPoint)
{
successCheckPoint = row.Text.Contains("Web User Login Success");
}
if (!failureCheckPoint)
{
failureCheckPoint = row.Text.Contains("Web User Login Failure");
}
}
}
感谢大家的帮助!这是我确定的代码版本:
Boolean successCheckPoint = false;
Boolean failureCheckPoint = false;
Boolean timeFound = false;
foreach (var row in auditRows)
{
if (row.Text.Contains(sCurrentTime) || row.Text.Contains(sLenientTime) || row.Text.Contains(sLenientTime2))
{
successCheckPoint |= row.Text.Contains("Web User Login Success");
failureCheckPoint |= row.Text.Contains("Web User Login Failure");
}
if (successCheckPoint && failureCheckPoint)
{
break;
}
}