gpt4 book ai didi

C# GOTO 在这个例子中是如何工作的(不符合预期)?

转载 作者:太空宇宙 更新时间:2023-11-03 19:20:02 25 4
gpt4 key购买 nike

这段 C# 代码很简单:

这段代码的场景:

当单词匹配时会产生意外的输出:

找到这个词找不到这个词found的值为:True

当单词不匹配时,它会产生预期的输出:

找不到这个词found的值为:False

    static void Main()
{
string[] words = { "casino", "other word" };

Boolean found = false;
foreach (string word in words)
{
if (word == "casino")
{
found = true;
goto Found;
}
}

if(!found)
{
goto NotFound;
}

Found: { Console.WriteLine("The word is found"); }
NotFound: { Console.WriteLine("The word is not found"); }

Console.WriteLine("The value of found is: {0}", found);

Console.Read();
}

最佳答案

goto 语句只是将执行移至该点。因此,在您的情况下,正在执行 Found,然后正在执行下一行 NotFound。

要使用 goto 解决此问题,您必须有第三个 goto,类似于 Continue。

static void Main()
{
string[] words = { "casino", "other word" };

Boolean found = false;

foreach (string word in words)
{
if (word == "casino")
{
found = true;
goto Found;
}
}

if(!found)
{
goto NotFound;
}

Found: { Console.WriteLine("The word is found"); goto Continue; }
NotFound: { Console.WriteLine("The word is not found"); }

Continue:
Console.WriteLine("The value of found is: {0}", found);

Console.Read();
}

不过我更喜欢这样的东西:

static void Main()
{
string[] words = { "casino", "other word" };

Boolean found = false;

foreach (string word in words)
{
if (word == "casino")
{
found = true;
break;
}
}

if(!found)
{
Console.WriteLine("The word is not found");
}
else
{
Console.WriteLine("The word is found");
}

Console.WriteLine("The value of found is: {0}", found);

Console.Read();
}

甚至更好!

static void Main()
{
string[] words = { "casino", "other word" };

if (words.Contains("casino"))
{
Console.WriteLine("The word is found");
}
else
{
Console.WriteLine("The word is not found");
}

Console.Read();
}

关于C# GOTO 在这个例子中是如何工作的(不符合预期)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13107904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com