【问题标题】:Cleaning up with IDisposable issues清理 IDisposable 问题
【发布时间】:2023-04-07 22:37:01
【问题描述】:

我试图调用这些函数来摆脱我不需要的东西,但我的代码似乎在我开始认为是徒劳的斗争中打败了我。我尝试了多种方法来解决最后两个错误,但 IEnumerator 给了我通配符。错误在行: if (enumerator2 是 IDisposable) 和 if (枚举数是 IDisposable)

        try
        {
            enumerator = matchs.GetEnumerator();
            while (enumerator.MoveNext())
            {
                IEnumerator enumerator2;
                Match current = (Match) enumerator.Current;
                num = 0;
                try
                {
                    enumerator2 = current.Groups.GetEnumerator();
                    while (enumerator2.MoveNext())
                    {
                        Group group = (Group) enumerator2.Current;
                        strArray[num, num3] = group.Value;
                        num++;
                    }
                }
                finally
                {
                    if (enumerator2 is IDisposable)
                    {
                        (enumerator2 as IDisposable).Dispose();
                    }
                }
                if (num2 < num3)
                {
                    num2 = num3;
                }
                num3++;
            }
        }
        finally
        {
            if (enumerator is IDisposable)
            {
                (enumerator as IDisposable).Dispose();
            }
        }
        strArray[num, 0] = Conversions.ToString((int) (num2 + 1));
        return strArray;
    }

编辑-特定的错误消息: 使用未分配的局部变量“enumerator2”
使用未赋值的局部变量 'enumerator'

【问题讨论】:

  • 您需要发布具体的错误信息
  • 您是否有理由直接使用枚举器而不是使用更惯用的 foreach 循环?另外,请查看using 声明。
  • (enumerator2 as IDisposable).Dispose(); 行可能是个问题。它基本上意味着“如果它是一次性的,则在 enumerator2 上调用 Dispose。否则在 null 上调用 Dispose”。如果你使用正确的语法((IDisposable)enumerator2).Dispose(),你的工具会更快乐。
  • IEnumerator 的泛型版本继承自IDisposable,所以它会让你的代码更简单。

标签: c# regex idisposable ienumerator dispose


【解决方案1】:

使用 for-each 循环而不是 while 循环。如果需要,它会为您调用 Dispose。

http://msdn.microsoft.com/en-us/library/aa288257(VS.71).aspx

【讨论】:

    【解决方案2】:

    您应该使用其他人指出的foreach 循环。

    但是,您收到该错误的原因是因为在 finally 块中使用 enumerator2 时,编译器无法知道它被设置为某个值(因为它可能不会在某些特殊情况下)。您可以通过执行以下操作按原样修复代码:

    IEnumerator enumerator2 = null;
    Match current = ...
    

    【讨论】:

    • 这是我对这个问题所需要的确切答案,即使它不是最有效的方法,ty。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多