What is System.Void?

醉酒当歌 提交于 2019-11-26 13:35:03

问题


I know that methods declared with void does not return anything.

But it seems that in C# void is more then just a keyword, but a real type.
void is an alias for System.Void like int that is for System.Int32.

Why am I not allowed to use that type? It does not make any sense, but this are just some thoughts about the logic.

Neither

var nothing = new System.Void();

(which says i should use void (Not an alias?))
nor

var nothing = new void();

compiles.

It is also not possible to use something like that:

void GiveMeNothing() { }
void GiveMeNothingAgain()
{
    return GiveMeNothing();
}

So whats the point with System.Void?


回答1:


From the documentation:

The Void structure is used in the System.Reflection namespace, but is rarely useful in a typical application. The Void structure has no members other than the ones all types inherit from the Object class.

There's no reason really to use it in code.

Also:

var nothing = new void();

This doesn't compile for me. What do you mean when saying it "works"?

Update:

A method void Foo() does not return anything. System.Void is there so that if you ask (through Reflection) "what is the type of the return value that method?", you can get the answer typeof(System.Void). There is no technical reason it could not return null instead, but that would introduce a special case in the Reflection API, and special cases are to be avoided if possible.

Finally, it is not legal for a program to contain the expression typeof(System.Void). However, that is a compiler-enforced restriction, not a CLR one. Indeed, if you try the allowed typeof(void) and look at its value in the debugger, you will see it is the same value it would be if typeof(System.Void) were legal.




回答2:


void/System.Void is different from int/System.Int32, it's a special struct in C#, used for reflection only. See this example:

class Program
{
   public static void Main(string[] args)
   {
      Type voidType = typeof(Program).GetMethod("Main").ReturnType;
   }
}

There must some type used to describe the return type of Main method here, that's why we have the System.Void.




回答3:


We have used the following code

public Type GetType(object o)
{
    var type = o == null ? typeof(void) : o.GetType();
}

So that we can use the null object pattern. It's pretty good. This allows us to do stuff like

GetType(o).GetProperties().Select( .....

instead of putting guard clauses everywhere




回答4:


Beyond not returning a value, very little definition is given of void (although void* gets some attention) in the language spec. This isn't really a language concern - although the CLI may define it further.

Ultimately though: because it has no meaning to do new void()



来源:https://stackoverflow.com/questions/5450748/what-is-system-void

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!