fxcop 分析为 foreach
行上的以下方法体提供了 CA2202 警告:
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();
}
}
Warning CA2202 Object 'steps.GetEnumerator()' can be disposed more than once in method 'LoggingService.LogAnalysis(IEnumerable, bool)'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.: Lines: 34
我做了一些研究,发现嵌套 using
语句和Dispose
调用导致分析器异常并发出此警告,但我既没有显式 Dispose
调用,也没有using
block 。我还没有遇到过针对 foreach
循环弹出此警告的其他情况。我知道如何抑制警告,但我只是想了解这可能是什么原因?
最佳答案
根据 canton7 的评论,我意识到当您使用菜单 Analyze>Run Code Analysis 强制代码分析时,它会强制使用旧的二进制 fxcop 即使您安装了新的 Roslyn Nuget 包强>.新的分析器在构建时自动使用,当我使用新的分析器时,问题中提到的警告消失了。
关于c# - CA2202 ForEach 循环警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58285762/