Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 错误消息";“检测到无法访问的代码”;夏普_C#_Decrement - Fatal编程技术网

C# 错误消息";“检测到无法访问的代码”;夏普

C# 错误消息";“检测到无法访问的代码”;夏普,c#,decrement,C#,Decrement,为什么编译器会给出错误消息“无法访问的代码”? 我想在这个链表中用-1递减整数变量nElements public object Pop() { if (StackEmpty()) throw new Exception("Error: No nodes to pop from stack"); object RemoveItem = headNode.Data; if (headNode == tailNode) headNode

为什么编译器会给出错误消息“无法访问的代码”? 我想在这个链表中用-1递减整数变量
nElements

public object Pop()
{
    if (StackEmpty())
        throw new Exception("Error: No nodes to pop from stack");

    object RemoveItem = headNode.Data; 

    if (headNode == tailNode)
        headNode = tailNode = null;
    else 
        headNode = headNode.Next;

    return RemoveItem;
    nbElements--;                 //Here is where the problem is
}

如果有return语句,函数将返回,并且return语句之后的任何代码都无法访问

简单的解决方案是将函数更改为将return作为函数中的最后一行

public object Pop()
{
    if (StackEmpty())
    throw new Exception("Error: No nodes to pop from stack");
    object RemoveItem = headNode.Data; 
    if (headNode == tailNode)
        headNode = tailNode = null;
    else headNode = headNode.Next;
    nbElements--;  
    return RemoveItem;        
}
顺便说一句,在if语句块周围使用大括号通常被认为是一种很好的做法。虽然不是严格必要的,但它清楚地说明了在条件之后将执行什么,并有助于避免以后添加不按预期流动的代码。下面是它的外观:

public object Pop()
{
    if (StackEmpty())
    {
        throw new Exception("Error: No nodes to pop from stack");
    }
    object RemoveItem = headNode.Data; 
    if (headNode == tailNode)
    {
        headNode = tailNode = null;
    }
    else
    {
        headNode = headNode.Next;
    }
    nbElements--;  
    return RemoveItem;        
}
至少,缩进代码

headNode = headNode.Next;
去别的地方,但是

return RemoveItem;
不在else中,所以它返回。方法停止并

nbElements--; 
遥不可及



因此,您只需交换“return removietem;”和“nbElements--;”

您的代码如下所示:

public object Pop()
{
    if (StackEmpty())
    throw new Exception("Error: No nodes to pop from stack");
    object RemoveItem = headNode.Data; 
    if (headNode == tailNode)
        headNode = tailNode = null;
    else headNode = headNode.Next;
    nbElements--;  
    return RemoveItem;
}

您在递减变量之前返回了
return
?返回之后不能有这样的语句。如果您希望在else中执行多个语句,请将if条件语句包装在
{}else{}
周围,避免
lzay格式化
对于
代码块
IMO,好的做法是只为if和else中的一行命令添加表格。牙套是unnecessary@lenden不必要的,但它绝对清楚什么作为if语句的一部分执行,并减少了以后引入bug的机会。当然,如果你是一个体面的程序员,那么缩进就足够了。但对于新人(正如OP所明确指出的那样),添加大括号可以避免以后的许多麻烦。很难不同意:)