简体   繁体   English

C#我想用out参数传递一个函数,不能使用数据类型void?

[英]C# I thought to pass a function using the out parameter, data type void couldn't be used?

So on my quiz for my c# course one of the questions was所以在我的 c# 课程测验中,问题之一是

How would you declare a function that requires the calling code to modify the original contents of an input parameter?您将如何声明一个需要调用代码修改输入参数原始内容的函数?

And for some reason the answer is出于某种原因,答案是

void mystery(out double clue)虚空之谜(出双线索)

I thought to use the out parameter you must use the same data type as the variable?我想使用 out 参数必须使用与变量相同的数据类型? So like this所以像这样

double mystery(out double clue)双谜(出双线索)

So, let consider the following pseudo-code:因此,让我们考虑以下伪代码:

R foo(T)

The function receives something of type T as input parameter.该函数接收类型为 T 的东西作为输入参数。 Also it returns something as a result of type R. In your quiz, the question was about T. So, the only way to let foo() to modify input parameter T is to add special signature around the T:它还返回 R 类型的结果。在您的测验中,问题是关于 T。因此,让 foo() 修改输入参数 T 的唯一方法是在 T 周围添加特殊签名:

R foo1(out T t) {...}
R foo2(ref T t) {...}

Well, actually there are two ways to do that, you see?嗯,实际上有两种方法可以做到这一点,你明白吗? The difference is: foo1 can accept non-initialized values and then set them to proper value inside foo1() code.区别在于: foo1 可以接受未初始化的值,然后在 foo1() 代码中将它们设置为正确的值。 However, foo2 requires the parameter to be initialized before calling foo2().但是,foo2 要求在调用 foo2() 之前初始化参数。 Because null value can not be referenced, thus can not be modified.因为空值不能被引用,因此不能被修改。

And, as kindly emphasized by Hans Kesting in comments below, "out" means "requires the calling code to modify the original contents of an input parameter".而且,正如 Hans Kesting 在下面的评论中所强调的那样,“out”意味着“需要调用代码修改输入参数的原始内容”。 So, this is it.所以,就是这样。

See these link for more details:有关更多详细信息,请参阅这些链接:

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

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