for 循环 - "Unreachable code detected" - 测试

for loop - "Unreachable code detected" - Test

我有以下测试需要通过:

[TestMethod]
public void ShouldRepeatANumberOfTimes()
{
    Simon simon = new Simon();
    Assert.AreEqual("hello hello hello", simon.Repeat("hello", 3)); 
    //So if parameter 3 was to be exchanged with 7, it would write "hello" seven times in one sentence.
}

对于这个作业,我认为 for 循环是一个自然的解决方案。所以我尝试了这个:

internal object Repeat(string v1, int v2)
{
    for (int i = 0; i < v2; i++)
    {
        return "hello ";
    }

    return v1;
}

我收到以下错误:

Unreachable code detected.

具体来说,i++中的i下面有一个"error line"。任何人都能够发现什么是错误的?提前致谢。

您将无法到达行 'return v1',因为您的 for 循环中有行 'return "hello"'。因此,您的程序在 for 循环中退出。

在第一次迭代 (i=0) 之后,您的方法是 returning return "hello ";,因此永远不会执行 i++。此外,您将无法访问 return v1 行,因为您已经 return 编辑了其他内容。看起来你想要 return (hello v2 次 + v1),所以你的代码应该是这样的(注意 yield return 用法):

internal IEnumerable<string> Repeat(string v1, int v2)
{
    for (int i = 0; i < v2; i++)
    {
        yield return "hello ";
    }

    yield return v1;
}

它应该有效

internal object Repeat(string v1, int v2)
{
    var str = "";

    for (int i = 0; i < v2; i++)
    {
        str += " " + v1;
    }

    return str.Trim();

}

由于您总是在第一次迭代期间返回一些东西,所以您只运行循环一次。因此,您的 for 循环中的 i++ 永远不会执行。

此外,正如 Devin Liu 正确指出的那样,从循环内部返回某些内容也会使 return v1 从外部无法访问,因为您之前(再次总是)返回某些内容。

你遇到的问题比那个错误还多:

在你的循环中,你总是 return "hello ",不管 v1.

你 return "hello " 在你的第一次迭代中,因此它永远不会到达 return v1;

如果您将 0 作为第二个参数传递,它仍然会 return v1 一次(来自最后一次 return 调用)。

即使在修复该函数后,如果将其调用为 simon.Repeat("hello", 3),结果仍将是 "hellohellohello".

您可以修复函数重写为:

    String reps = String.Empty;

    for (int i = 0; i < v2; i++)
    {
        reps = string.Concat(reps, v1);
    }

    return reps;

你的测试为:

    Assert.AreEqual("hellohellohello", simon.Repeat("hello", 3)); 

如其他人所述,您的函数将始终以这一行结束

return "hello ";

要重复你的字符串,你可以使用类似这样的东西而不需要任何循环。

return string.Join(" ", Enumerable.Repeat("Hello", 2));

只需将这一行放在您的函数中,并将 Hello2 替换为您的参数

此方法将 return 一个字符串而不是一个列表,并添加正确数量的 space,因为测试用例没有尾随 space。

internal object Repeat(string v1, int v2)
{

    var output = string.empty;
    for (int i = 0; i < v2; i++)
    {
        output += v1;
        if(i <= v2-1)
        {
            output += " ";
        }
    }

    return output ;
}

我推荐的其他一些方法: 如果您认为您将构建非常大的字符串,我建议改用 StringBuilder,我不只是为了尽可能快地编写它。 您也可以删除循环末尾的尾随 space,我只是不想从一开始就添加它。