简体   繁体   English

遗漏“虚空”一词与包括“虚空”一样吗?

[英]Is leaving out the word Void the same as including Void?

Are these the same? 这些都一样吗?

public void MyMethod() {do something}

public MyMethod() {do something}

void means return nothing - so leaving this key word out also means return nothing? void表示什么都不返回-因此省略此关键字还意味着什么都不返回吗? If this is the case then why does the word exist in the language - is it used in other situations? 如果是这种情况,那么为什么该单词在语言中存在-是否在其他情况下使用它?

Your second option doesn't compile. 您的第二个选项无法编译。

C# specs requires that every method returns a type also when there is no result to return. C#规范要求,当没有结果要返回时,每个方法也都返回一个类型。

Methods are declared within a class or struct by specifying the access level, the return value , the name of the method, and any method parameters. 通过指定访问级别, 返回值 ,方法名称和任何方法参数,可以在类或结构中声明方法。 ... ...

As noted by others the exception are class constructors. 正如其他人所指出的那样,类构造函数是例外。

Methods (C# Programming Guide) on MSDN . MSDN上的方法(C#编程指南)

You always must specify a return type for your methods regardless that its void or a type. 始终必须为您的方法指定一个返回类型,而不管其为空还是类型。 Exceptions include constructors. 异常包括构造函数。

You can not do the second case in C# , it wil not compile. 您无法在C#进行第二种情况,因此无法编译。 In C# , you should always specify esplicitly return type, even if it's "nothing". C# ,即使“ nothing”也应始终明确指定返回类型。

想想void是没有返回值的占位符,同时保持语法与具有返回类型的函数/方法兼容。

The first line is a public instance method . 第一行是public实例方法 It can only occur inside a class (or struct ) that is not c itself called MyMethod . 它只能在本身不是 c的class (或struct )中称为MyMethod

The second example is a public instance constructor . 第二个示例是public实例构造函数 It can occur inside a class which is itself called MyMethod (a strange name for a class, though). 它可以发生在一个本身称为MyMethod的类中(尽管这是一个class的奇怪名称)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM