Is 'void' a valid return value for a function?

匿名 (未验证) 提交于 2019-12-03 03:08:02

问题:

private void SaveMoney(string id...) {     ... }  public void DoSthWithMoney(string action,string id...) {     if(action=="save") return SaveMoney(string id);     ... }

Why won't C# let me return the void of the private function back through the public function? It even is the same data type "void"...

Or isn't void a data type?

Is the following code really the shortest workaround?

if(action=="save") {     SaveMoney(string id);     return; }

回答1:

void is not an actual return (data)type! void says there is no result. So you can not return a value in a method that's declared void even though the method you're calling is also declared void.

I must admit it would be a nice shortcut, but it's not how things work :-)


Just an additional thought: If what you want was allowed, void would become both a data type and also the only possible value of that data type, as return x; is defined as returning the value x to the caller. So return void; would return the value void to the caller - not possible by definition.

This is different for null for example, as null is a valid value for reference types.



回答2:

void is not a type in C#. In this instance, void means the absence of a return type or value so you cannot use it with return as you have in the first example.

This is different to C, for example, where void can mean typeless or an unknown type.



回答3:

That is not a workaround, it is the right way to do it.



回答4:

Even if this would compile I wouldn't recommend it. In such a small method, it's clear what's going on, but if it's a bigger method, the next programmer is going to see that, blink, think "I thought this was a void method" scroll up, confirm that, scroll back down, follow the SaveMoney method, find out it returns nothing, etc.

Your "workaround" makes that clear at a glance.



回答5:

Just change the method to a boolean and return 0.



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