c# - 如果使用 out 参数,调用范围中的变量何时更改?

标签 c# asynchronous specifications 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 ?

如果我想转达当前实现的行为,是否有任何规范?

最佳答案

一旦在函数中分配了 A,它就会被分配。 out 的使用提供了对您传入的任何内容的引用,这意味着只要它在方法中被修改,它就会被修改。

C# 语言规范的摘录:

5.1.6 Output parameters

A parameter declared with an out modifier is an output parameter.

An output parameter does not create a new storage location. Instead, an output parameter represents the same storage location as the variable given as the argument in the function member or delegate invocation. Thus, the value of an output parameter is always the same as the underlying variable.

The following definite assignment rules apply to output parameters. Note the different rules for reference parameters described in §5.1.5.

· A variable need not be definitely assigned before it can be passed as an output parameter in a function member or delegate invocation.

· Following the normal completion of a function member or delegate invocation, each variable that was passed as an output parameter is considered assigned in that execution path.

· Within a function member or anonymous function, an output parameter is considered initially unassigned.

· Every output parameter of a function member or anonymous function must be definitely assigned (§5.3) before the function member or anonymous function returns normally.

Within an instance constructor of a struct type, the this keyword behaves exactly as an output parameter of the struct type (§7.6.7).

关于c# - 如果使用 out 参数,调用范围中的变量何时更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7659453/

相关文章:

c# - 将 Enum 转换为 uint

Node.js for 循环内的 for 循环

javascript - 什么是 ECMAScript 6 WeakMaps?

针对 w3c 规范的浏览器更新

java - 定义 : Unfinalized versus finalizable object

c# - 向安装添加应用程序启动选项(复选框)

c# - Mono/.NET 4.0 是否实现 AppDomain.FirstChanceException?

c# - 是否可以在应用程序设置中使用自定义枚举? (VS10)

grails - Grails,Promise API和两个公开 session

c# - 进行长时间运行的异步调用就这么简单吗?