C# 检测到无法访问的代码?

C# 检测到无法访问的代码?,c#,C#,我发现了这个无法到达的错误代码,并且清楚地看到了所有的东西 这是密码 int lastAppNum = 0; //load the xml document XmlDocument xdoc = new XmlDocument(); xdoc.Load(GlobalVars.strXMLPath); //add a app node XmlNode newApp = xdoc.CreateNode(XmlNodeType.Element, "app", null);

我发现了这个无法到达的错误代码,并且清楚地看到了所有的东西

这是密码

int lastAppNum = 0;

//load the xml document            
XmlDocument xdoc = new XmlDocument();
xdoc.Load(GlobalVars.strXMLPath);

//add a app node
XmlNode newApp = xdoc.CreateNode(XmlNodeType.Element, "app", null);

//add the app number - this will be used in order to easily identify the app details (used for overwriting/saving)
XmlAttribute newNum = xdoc.CreateAttribute("num");

//in order to create a new number - search the last num and add one to it 
foreach (XmlNode xmlAppChild in xdoc.ChildNodes)
{         
    //if there are existing child nodes
    if (true)
    {                   
        //get the last childs num attribute
        lastAppNum = Convert.ToInt32(xmlAppChild.LastChild.Attributes["num"].Value);

        //add +1 to the last app num
        lastAppNum++;

        //add the new value to the attribute
        newNum.InnerText = lastAppNum.ToString();

        break;

    }else{
        //if there isnt an existing child node - set the num to 1
        lastAppNum = 1; <<where the error happens
        newNum.InnerText = lastAppNum.ToString();
        break;

    }

}
有人知道发生了什么吗?我想可能是因为缺少休息,所以我在这里投了两个,我看到了一个表格,这就是解决方案,但不管怎样都不重要,错误还在发生。任何建议都会很好。

如果是真的,你有什么条件需要测试吗

if (true)
{
    // this code will always run
}
else
{
    // this code will never run
}
代码

  if (true)
将始终执行,并且没有机会执行else条件。

else条件将永远不会运行,因为您有if true

我认为根据您的评论,您需要如下更改实现

if(xdoc.HasChildNodes)
{
    foreach (XmlNode xmlAppChild in xdoc.ChildNodes)
    {         

        //if there are existing child nodes                
        //get the last childs num attribute
        lastAppNum = Convert.ToInt32(xmlAppChild.LastChild.Attributes["num"].Value);

        //add +1 to the last app num
        lastAppNum++;

        //add the new value to the attribute
        newNum.InnerText = lastAppNum.ToString();

    }
}else
{

    //if there isnt an existing child node - set the num to 1
    lastAppNum = 1; 
    newNum.InnerText = lastAppNum.ToString();
}

iftrue可能始终为true:@user3302467:如果将警告级别设置正确,则无法访问的代码不是错误。这更像是对用户的一个警告,你可能写了一些非预期的东西。这不是所有的警告都是这样吗?为什么它们都应该被视为错误?看起来,如果真的话,你需要改变一个条件,这个条件的含义与此相同:如果存在子节点,这是有意义的。是的,我忘了在里面放一个条件陈述。哎呀!