IDE0059 给“i”分配了不必要的值

Ive*_*Ive 7 c# visual-studio-2019

此代码在 Visual Studio 2019 中生成信息消息:*严重性代码描述项目文件行抑制状态抑制状态详细描述消息 IDE0059

将值不必要地分配给“i”

避免在您的代码中进行不必要的赋值,因为这些可能表示冗余值计算。如果值计算不是多余的并且您打算保留赋值,则将赋值目标更改为名称以下划线开头并可选后跟整数的局部变量,例如“_”、“_1”、“_2” ' 等。这些被视为特殊的丢弃符号名称。*

代码片段工作正常,这是消息 IDE0059,让我烦恼。如果可能的话,我不想压制它。

    private static XmlDocument LoadXmlFromFile(string xmlPath)
    {
        XmlDocument doc = new XmlDocument();
        int i = 2;
        while (true)
        {
            try
            {
                using (Stream fileStream = System.IO.File.Open(xmlPath, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    doc.Load(fileStream);
                }

                return doc;
            }
            catch (IOException) when (i > 0)
            {
                i--;
                Thread.Sleep(100);

            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

这里有什么问题?是误报还是我错过了什么?

此代码还在 VS2019 中产生警告 IDE0059:

private static XmlDocument LoadXmlFromFile(string xmlPath)
    {
        XmlDocument doc = new XmlDocument();
        int i = 2;
        while (true)
        {
            try
            {
                using (Stream fileStream = File.Open(xmlPath, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    doc.Load(fileStream);
                }

                return doc;
            }
            catch (IOException)
            {
                if (i == 0)
                {
                    throw;
                }
                i--;
                Thread.Sleep(100);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Jac*_*SFT 3

根据您的描述,您似乎想在经历过睡眠后结束睡眠。

两个异常而不抛出警告。

我建议你可以使用if语句来做到这一点。

class Program
{
    static void Main(string[] args)
    {
        string path = "D:\\teest1.xml";
        var doc = LoadXmlFromFile(path);
    }
    private static XmlDocument LoadXmlFromFile(string xmlPath)
    {
        XmlDocument doc = new XmlDocument();
        int i = 2;
        while (i>=0)              // change the while sentence
        {
            try
            {
                using (Stream fileStream = System.IO.File.Open(xmlPath, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    doc.Load(fileStream);
                }

                return doc;
            }
            catch (IOException ex)
            {             
                if (i == 0)
                {
                    throw ex;
                }

                i--;
                Thread.Sleep(200);
            }

        }
        return doc;
    }

}
Run Code Online (Sandbox Code Playgroud)