c# - CA2202 ForEach 循环警告

标签 c# fxcop ca2202

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/

相关文章:

visual-studio-2010 - 将警告视为错误无效

c# - VS2005代码分析: CA1063 (call dispose(true) and supress finalize) - with logging

sql - 如何处理这个SQL注入(inject)警告(CA2100)

.net - 如何在没有代码分析警告的情况下一起使用 StringWriter 和 HtmlWriter

C# 验证 : IDataErrorInfo without hard-coded strings of property name?

java - C# 和 Java Web 服务集成

c# - 是否可以在 SelectedIndexChanged 事件触发回发时重新绑定(bind) DropDownList?

c# - 使用 ViewBag 时出现 RuntimeBinderException

c# - 基于不适用于 System.Web.UI.Control 对象的 CA2000 "Dispose Objects Before Losing Scope"创建自定义 FXCop 规则