This question already has answers here:
Missing return statement in a non-void method compiles

(13个回答)


4年前关闭。




我一直认为,与void不同的方法必须返回一个值,无论如何,例如,如果我们有此方法
    private int Foo()
    {
        while (true)
        {

        }
    }

这里没有编译时错误,我认为这是因为循环是无限的,C#可以保证它不会终止而不返回值。我对么 ?

最佳答案

只有带有reachable端点的非空函数才必须返回一个值。

有关更多信息,请检查Eric Lippert的this answer

关于c# - 有趣的代码片段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41081184/

10-11 20:15