简体   繁体   English

'void'是函数的有效返回值吗?

[英]Is 'void' a valid return value for a function?

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? 为什么C#不允许我通过公共函数返回私有函数的空白? 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;
}

void is not a type in C#. void不是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. 在这种情况下, void表示没有返回类型或值,因此您不能像第一个示例中那样使用return

This is different to C, for example, where void can mean typeless or an unknown type . 这与C不同,例如,void可以表示无类型或未知类型

void is not an actual return (data)type! void 不是实际的返回(数据)类型! void says there is no result. void没有结果。 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 . 因此,即使您调用的方法也声明为void也无法在声明为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; 只是另外一个想法:如果你想要的是什么,那么void将成为一种数据类型也是该数据类型唯一可能的值,如return x; is defined as returning the value x to the caller. 定义为将值x返回给调用者。 So return void; 所以return void; would return the value void to the caller - not possible by definition. 会将值void返回给调用者 - 根据定义,这是不可能的。

This is different for null for example, as null is a valid value for reference types. 这是针对不同的null例如作为null为引用类型的有效值。

这不是一种解决方法,它是正确的方法。

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. 在这么小的方法中,很明显发生了什么,但如果它是一个更大的方法,下一个程序员会看到,眨眼,认为“我认为这是一个无效的方法”向上滚动,确认,向下滚动,按照SaveMoney方法,找出它什么也不返回,等等。

Your "workaround" makes that clear at a glance. 您的“解决方法”一目了然。

只需将方法更改为布尔值并返回0。

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

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