作为具有任何返回类型的函数体有效的语句



这个问题(或者更具体地说,这个答案)让我想知道:在C#中,作为具有任何返回类型的函数体,哪些语句是有效的?

例如:

public void Foo()
{
    while (true) { }
}
public int Foo()
{
    while (true) { }
}

这两个函数都是有效的C#函数,即使第二个函数并没有真正返回int

所以我知道无限循环(例如for(;;))和类似throw new Exception()的throw语句作为任何函数的主体都是有效的,但有更多具有该属性的语句吗?


更新:

我想到了另一个解决方案,一个无限递归:

    public string Foo()
    {
        return Foo();
    }

有趣的是,一个与第二个代码段没有什么不同的例子是:

public static int Foo()
{
    do {}
    while (true);
}

但我不认为这真的算"不同"。

另外,goto是邪恶的另一个例子:

public static int Foo()
{
    start:
    goto start;
}

值得注意的是,这确实会导致编译错误:

public static int Foo()
{
    bool b = true;
    while (b) 
    {
    }
}

即使b没有改变。但如果您显式地使其恒定:

public static int Foo()
{
    const bool b = true;
    while (b) 
    {
    }
}

它又起作用了。

它与goto示例几乎相同,但涉及switch

public int Foo()
{
    switch (false)
    {
         case false:
         goto case false;
    }
}

不确定这是否符合新的条件。

有趣的是,以下内容无法编译:

public static int Foo(bool b)
{
    switch (b)
    {
        case true:
        case false:
            goto case false;
    }
}

显然,编译器不知道布尔值只能有两个可能的值。您需要明确涵盖所有"可能"的结果:

public static int Foo(bool b)
{
    switch (b)
    {
        case true:
        case false:
        default:
            goto case true;
    }
}

或者以最简单的形式:

public static int Foo(bool b)
{
    switch (b)
    {
        default:
            goto default;
    }
}

是的。。。我今天工作无聊。

非无效&无CCD_ 8;

public IEnumerable Foo()
{
    yield break;
}

最新更新