如果使用 out 参数,何时更改调用范围中的变量?
我现在无法尝试,但我确信,有人知道:
void func(out MyType A) {
A = new MyType();
// do some other stuff here
// take some time ... and return
}
当我以这样的异步方式调用它时:
MyType a;
func(out a);
一旦在函数中分配了 A , a 会立即更改吗?或者仅当函数返回时才将新对象引用分配给 a ?
如果我想继承当前实现的行为,是否有任何规范?
I cannot try rigth now, but I am sure, someone knows:
void func(out MyType A) {
A = new MyType();
// do some other stuff here
// take some time ... and return
}
When I call this in an asynchronous manner like that:
MyType a;
func(out a);
will a be altered immediately, once A is assigned in the function? Or is the new object reference assigned to a only when the function returns?
Are there any specifications if I want to relay on the currently implemented behavior?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一旦 A 在函数中被赋值,它就被赋值。
out
的使用提供了对您传入的任何内容的引用,这意味着只要在方法中修改它,它就会被修改。C# 语言规范摘录:
It's assigned once A is assigned in the function. The use of
out
provides a reference to whatever you passed in, which means it gets modified whenever it is modified in the method.An extract from the C# language spec:
一旦线程执行 A = new MyType(); 就会改变它
It will be changed as soon as thread excecute A = new MyType();
此处也描述了 out,但是一个简短的测试将向您展示什么你需要足够快地知道:
输出:
编辑:根据您的评论,让我添加以下内容:
正式语言out 关键字的规范文档 不仅限于其他答案之一中所述的第 5.1.6 章,而且还包括第 10.6.1.3 章(第 307 页)如下:
您一定会对本节感兴趣
它清楚地表明该参数没有自己的存储位置,因此在函数中更改它的值将更改原始值。
out is also described here but a short and simple test will show you what you need to know fast enough:
output:
EDIT: Based on your comment let me add the following:
The formal language specification documentation for the out keyword is not limited to chapter 5.1.6 as stated in one of the other answers but also covered in chapter 10.6.1.3 (p 307) as follows:
what's bound to be of interest to you is this section
which clearly states the parameter has no storage location of its own, so altering the value of it in your function will alter the value of the original instead.
这里是一个问题关于引用和线程安全,结论是它不是线程安全的。 out 几乎与 ref 相同(out 也支持空引用),并且它不是线程安全的事实意味着值会立即更改。
Here is a question about ref and thread safety, with the conclusion that its not thread safe. out is almost the same as ref (out supports also null references) and the fact that it's not threadsafe means the values are altered immediately.