簡體   English   中英

清理 IDisposable 問題

[英]Cleaning up with IDisposable issues

我試圖調用這些函數來擺脫我不需要的東西,但我的代碼似乎在我開始認為是徒勞的斗爭中打敗了我。 我嘗試了多種方法來解決最后兩個錯誤,但 IEnumerator 給了我通配符。 錯誤出現在: if (enumerator2 is IDisposable) 和 if (enumerator is 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”
使用未分配的局部變量“枚舉器”

使用 for-each 循環而不是 while 循環。 如果需要,它會為您調用 Dispose。

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

您應該使用其他人指出的foreach循環。

但是,您收到該錯誤的原因是因為在finally塊中使用enumerator2時,編譯器無法知道它被設置為某個值(因為它可能不會出現在某些特殊情況下)。 您可以通過執行以下操作按原樣修復代碼:

IEnumerator enumerator2 = null;
Match current = ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM