此代码在 Visual Studio 2019 信息消息中生成:
*Severity Code Description Project File Line Suppression State Suppression State Detail Description
消息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);
}
}
}
这里有什么问题?是误报还是我错过了什么?
此代码还在 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);
}
}
}
最佳答案
根据你的描述,你好像是想结束 sleep
没有抛出警告的两个异常。
我建议你可以使用 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;
}
}
关于c# - IDE0059 将值不必要地分配给 'i',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58872303/