goto语句如何在这个例子中起作用?

时间:2010-08-31 16:46:17

标签: c# goto

我正在研究此代码示例:

class Program
{
    static void Main(string[] args)
    {
        int x = 10;
        int y = 10;

        int generate=0;

        string [,] myArrayTable = new string[x, y];

        Console.WriteLine("Enter a seek number: ");
        string cautat = Console.ReadLine();

        for (int i = 0; i < x; i++)
        {
            for(int j = 0;j < y; j++)
            {
                myArrayTable[i, j] = (generate++).ToString();
            }
        }

        for(int i=0;i<x;i++)
        {
            for(int j=0;j<y;j++)
            {
                if(cautat.Equals(myArrayTable[i,j]))
                {
                    goto Found; 
                }
            }
        }

        goto NotFound;

        Found: 
          Console.WriteLine("Numarul a fost gasit");

        NotFound:
         Console.WriteLine("Numarul nu a fost gasit !");

        Console.ReadKey();
    }
}

我不明白为什么调用“Not Found”语句并在控制台上打印相应的消息,如果我输入一个10的搜索号,在这种情况下goto:Found语句正在执行,所以goto:NotFound语句永远不会调用,但仍然在控制台上打印相应的消息,我不明白,因为在这种情况下程序永远不会跳转到这个“NotFound”标签。

如果你现在帮我解决这个问题......

谢谢

6 个答案:

答案 0 :(得分:9)

Eww goto,我会使用和if/else声明,但是如果你需要goto的话:

Found: 
  Console.WriteLine("Numarul a fost gasit");
  goto End;
NotFound:
  Console.WriteLine("Numarul nu a fost gasit !");
End:
Console.ReadKey();

答案 1 :(得分:7)

我会重写此代码以避免使用goto:

string message;
if (myArrayTable.Cast<string>().Contains(cautat)) {
    message = "Found";
} else {
    message = "Not found!";
}
Console.WriteLine(message);

答案 2 :(得分:4)

它被调用是因为你的Found标签里面的代码没有任何东西强迫它跳过NotFound标签的代码(除非你再次调用goto,执行将通过标签而不是跳过它)。

话虽如此,不要使用goto我会尽可能地说它总是一个坏主意,可以重新写入。

在你的情况下,你可以添加一个简单的布尔标志来摆脱你的转到:

static void Main(string[] args)
{
    int x = 10, y = 10;
    bool isFound = false;

    // Rest of the body

    for(int i=0;i<x;i++)
    {
        for(int j=0;j<y;j++)
        {
            if(cautat.Equals(myArrayTable[i,j]))
            {
                isFound = true;
                break;
            }
        }

        if(isFound)
            break;
    }

    if(isFound)
        Console.WriteLine("Numarul a fost gasit");
    else
        Console.WriteLine("Numarul nu a fost gasit!");

    Console.ReadKey();
}

答案 3 :(得分:1)

因为您只是跳转到Found标签并继续进入Not Found标签。你需要一个名为EndFound的第三个标签,并在找到之后转到它。

Found: 
    Console.WriteLine("Numarul a fost gasit");
    goto EndFound;
NotFound:
    Console.WriteLine("Numarul nu a fost gasit !");
EndFound:

答案 4 :(得分:1)

如果您不希望执行“找到”状态执行“找不到”状态,请使用另一个转到,跳过NotFound部分。 goto跳转到某个部分,但这并不意味着如果未通过goto跳转到该部分,则不会执行该部分。请记住,代码以自上而下的方式执行,因此,除非您以某种方式跳过代码,否则它将执行。

示例:

Found:  
    Console.WriteLine("Numarul a fost gasit"); 

goto ReadKey;

NotFound: 
    Console.WriteLine("Numarul nu a fost gasit !"); 

ReadKey:
    Console.ReadKey(); 

答案 5 :(得分:0)

因为在跳转到Found之后,执行只会继续到下一行,这恰好是“未找到”控制台写入行。你需要添加另一个goto来跳过它(或者更好的是,重新设计它以完全避免使用它)

正是这样的问题,应该避免使用。