C#代码允许有趣的语法,也无效的方法可以让收益 [英] C# code allow fun syntax, and also void method can allowed return
问题描述
大家好我昨天交的一个问题:如C#允许; ; ; ; ; ; ; ; ; ; ; ; ( C#空语句)
和找到了答案:的http://计算器.COM / A /2218635分之20551989
但今天我看到了一个又一个有趣的(错误)
请参阅本下面的图片
为什么视觉工作室允许这样做?代码构建成功。为什么它的建立?
和另外一个有趣的代码始终运行
私人无效安装()
{
http://www.stackoverflow.com
的回报;
}
修改
请参阅上面的方法是一个无效的方法,我知道虚空方法不返回。但为什么它没有显示出任何错误?和余did't分配任何变量为 http://www.stackoverflow.com 。但它为什么不给我一个错误?
块引用>
解决方案该方法建立,因为它是完全有效的C#。
这些都是标签。他们是
转到
构建从C / C ++,使执行跳转到该方法中的一个特定点继承了C#。它的使用通常不鼓励。
从的 8.4标记语句
A 标记的声明允许一个标签作为前缀的声明。 。标记语句可以在块中,但不允许它们作为嵌入语句
的标记的声明的:
 的 标识符的语句的
一个标记语句声明了一个标签名称由标识符的说明。标签的范围是整个块,其中标签声明,包括任何嵌套块。这是两个标签具有相同的名称有重叠的范围,编译时错误。
块引用>
进一步阅读
关于更新的问题。请注意,有没有在
收益
语句提供的值。这是完全有效的以这种方式使用收益
A无效
方法中。简单地使执行停止和控制要传送回呼叫方。事实上,你可以认为具有然后结束将控制权返回给调用者隐式return语句的每个方法。
据的会 是一个错误,如果你试图返回一个特定的值:
返回0;
产生错误:
由于'MyPage.Page_Load返回void,返回关键字一定不能跟一个对象表达式
块引用>Hi All yesterday i was post one question : like c# allow ; ; ; ; ; ; ; ; ; ; ; ; (C# Empty Statement)
Why C# allow this fun? ; ; ; ;
and found the answer : http://stackoverflow.com/a/20551989/2218635
But today i saw another one fun(bug)
See this below image
Why visual studio allow this? Code build success. Why it's build?
and another one fun code always run
private void install() { http://www.stackoverflow.com return; }
Edit :
See above method is a void method , I know void method does not return . But Why it's not shown any error? and I did't assign any variable for the"http://www.stackoverflow.com".but why it's not give me a error ?
解决方案The method builds because it's perfectly valid C#.
Those are labels. They are part of the
goto
construct that C# inherited from C / C++ that allows execution to jump to a specific point within the method. It's use is generally discouraged.A labeled-statement permits a statement to be prefixed by a label. Labeled statements are permitted in blocks, but are not permitted as embedded statements.
labeled-statement:
identifier : statement
A labeled statement declares a label with the name given by the identifier. The scope of a label is the whole block in which the label is declared, including any nested blocks. It is a compile-time error for two labels with the same name to have overlapping scopes.
Further Reading
Regarding the updated question. Notice that there is no value supplied in the
return
statement. It's perfectly valid to usereturn
in this way within avoid
method. That simply causes execution to stop and the control to be transferred back the caller. In fact, you can think of every method having an implicit return statement at then end to return control back to the caller.It would be an error if you attempted to return a specific value:
return 0;
Produces the error:
Since 'MyPage.Page_Load' returns void, a return keyword must not be followed by an object expression
这篇关于C#代码允许有趣的语法,也无效的方法可以让收益的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!