我有一个对象,它使用一些底层 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/