fxcop 分析为以下方法主体提供CA2202 警告foreach
:
public void LogAnalysis(IEnumerable<string> steps, bool append = false)
{
if (steps != null)
{
StringBuilder sb = new StringBuilder();
try
{
foreach (string step in steps) // this is line 34
{
sb.AppendLine(step);
}
if (append)
{
sb.Insert(0, string.Format(
CultureInfo.InvariantCulture,
"__________Logging started at {0}__________\n",
DateTime.Now.ToString(CultureInfo.InvariantCulture)));
File.AppendAllText(AnalysisLogFile, sb.ToString());
}
else
{
File.WriteAllText(AnalysisLogFile, sb.ToString());
}
}
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
{
LogError(e.Message);
}
sb.Clear();
}
}
警告 CA2202 对象“steps.GetEnumerator()”可以在方法“LoggingService.LogAnalysis(IEnumerable, bool)”中多次处理。为避免生成 System.ObjectDisposedException,您不应在对象上多次调用 Dispose。:行:34
我做了一些研究,发现嵌套 using
语句和Dispose
调用会导致分析器发疯并发出此警告,但我既没有显式 Dispose
调用也没有using
块。foreach
我还没有遇到过循环弹出此警告的另一种情况。我知道如何抑制警告,但我只是想了解这可能是什么原因?