[英]Why is return type void declared as struct in .NET?
AFAIK void
means nothing in terms of programming language. AFAIK
void
在编程语言方面没有任何意义。 So why in .Net framework it is declared as struct
? 那么为什么在.Net框架中它被声明为
struct
?
using System.Runtime.InteropServices;
namespace System
{
/// <summary>
/// Specifies a return value type for a method that does not return a value.
/// </summary>
/// <filterpriority>2</filterpriority>
[ComVisible(true)]
[Serializable]
[StructLayout(LayoutKind.Sequential, Size = 1)]
public struct Void
{
}
}
System.Void
is effectively a marker type - members like MethodInfo.ReturnType
have to have some way of representing void
, and System.Void
is the way the .NET team chose to do so. System.Void
实际上是一种标记类型 - 像MethodInfo.ReturnType
这样的成员必须有一些表示void
,而System.Void
是.NET团队选择这样做的方式。
You shouldn't use it like a normal type. 你不应该像普通类型一样使用它。 It's a workaround, effectively - a little like the F#
Unit
type , but not as fully integrated into the type system. 这是一种有效的解决方法 - 有点像F#
Unit
类型 ,但不完全集成到类型系统中。
A method descriptor contains a field for the method's return type. 方法描述符包含方法返回类型的字段。 While it would be possible to have that field be
null
for void
functions, that would require that code which wants to eg report the method's return type say something like: 虽然可以使该字段对于
void
函数为null
,但这需要想要报告方法的返回类型的代码如下所示:
string theReturnType = theMethod.ReturnType ? theMethod.ReturnType.ToString() : "null";
rather than simply saying: 而不是简单地说:
string theReturnType = theMethod.ReturnType.ToString();
There are enough cases where code has to do something with the method's return type that having to special-case null in all of them would be a far greater bother than simply having a dummy type "null" which can be returned. 有足够多的情况下,代码必须对方法的返回类型做一些事情,在所有这些方法中必须使用特殊情况null才会比仅仅返回可以返回的虚拟类型“null”更麻烦。
Incidentally, although so far as I know void
is the only type which is usable for a method return value but no other purpose, there are other cases where it would be useful to have a type which could be used for public return values, but not used in outside storage-location declarations, such as when writing a fluent interface (if outside code could be allowed to access members of biz.boz(3)
, but could not store the value itself, then in a construct like biz.boz(3).foo(9).bar(2).build()
, the foo
method could know that it held the only reference anywhere in the universe to the object returned by boz(3)
, and would thus be free to either mutate it or return a new instance, at its convenience). 顺便说一下,虽然我知道
void
是唯一可用于方法返回值但没有其他目的的类型,但在其他情况下,有一个类型可用于公共返回值是有用的,但不是用于外部存储位置声明,例如在编写流畅的界面时(如果允许外部代码访问biz.boz(3)
成员,但无法存储值本身,则在biz.boz(3).foo(9).bar(2).build()
等biz.boz(3).foo(9).bar(2).build()
, foo
方法可以知道它在宇宙中的任何地方都拥有boz(3)
返回的对象的唯一引用,因此可以自由地进行变异它或在方便时返回一个新实例)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.