c# - 如何处理通过 Next 属性迭代的对象?

标签 c# code-analysis ca2202

我有一个对象,它使用一些底层 native 资源,并且有一个指向下一个实例的指针,我对其进行迭代,类似于:

MyObject begin = null;

try
{
    begin = GetFirst();

    while (begin != null)
    {
        MyObject next = begin.Next();
        // do something with begin
        begin.Dispose();
        begin = next;
    }
}
finally
{    
    if (begin != null)
    {
        begin.Dispose();
    }
}

我遇到代码分析问题:

CA2202: Microsoft.Usage: Object 'begin' can be disposed more than once in method 'x()'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.

知道如何在不抑制它的情况下消除此错误吗?

最佳答案

在我看来,你的最后一段代码确实是不必要的。如果begin != null ,然后是你的while循环应该继续,不是吗?

更新:您似乎正在尝试确保 begin 的最后获得的值如果抛出异常则被处理。试试这个:

MyObject begin = GetFirst();

while (begin != null)
{
    MyObject next;
    using (begin)
    {
        next = begin.Next();
        // do something with begin
    }

    begin = next;
}

请注意,在上述建议中,实际上仍然可能会出现未处理对象的情况:分配给 next 的最后一个值,在 using 结束之前堵塞。您原来的问题中没有涵盖这种情况,因此我没有在上述建议中解决它。不过,如果这是一个潜在的问题,那么就值得考虑。

关于c# - 如何处理通过 Next 属性迭代的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3622832/

相关文章:

c# - 我们如何防止弹出窗口出现在应用程序顶部?

c# - ASP.Net MVC2 (RTM) 中断响应过滤 - "Filtering is not allowed"

c# - 在使用特定子类型调用时查找特定方法的用法

C#CA2000 :Dispose objects before losing scope using FileStream/XmlTextReader

c# - 使用 Nest 进行 Elasticsearch

c# - 使用 LINQ 将一行变成两个对象?

c++ - 如何比较相似的代码库?

c# - 代码分析规则 CA1040 : Avoid empty interfaces, 在非空接口(interface)上报错

c# - 多次处理对象