class fff {
public static void jjj(out int j) {
j = 88;
}
}
//Main method
int jfjf;
fff.jjj(out jfjf);
Run Code Online (Sandbox Code Playgroud)
在我的 main 方法中,我声明了jfjf在运行时未初始化的变量,因此我想知道当我将jfjf其作为 out 参数传递给我的方法时,方法中的 指的jjj(out int j)是什么,因为未初始化?
我想知道这在内部是如何运作的。int jjfjf
在内部,的地址jfjf被传递给您的方法。
对于常规(非输出)int 参数,参数的值将传递给方法。例如,以下代码块的第一条语句
f(1);
void f(int i) {
...
}
Run Code Online (Sandbox Code Playgroud)
编译为以下 CIL ( Sharplab ):
IL_0000: ldc.i4.1 // Push the value 1 on the stack
IL_0001: call void Program::'<<Main>$>g__f|0_0'(int32) // Invoke the method
Run Code Online (Sandbox Code Playgroud)
另一方面,如果我们有一个输出参数(sharplab):
f(out int i);
void f(out int i) {
i = 0;
}
Run Code Online (Sandbox Code Playgroud)
的地址被传递i到f:
IL_0000: ldloca.s 0 // Push the address of the local variable with index 0 on the stack
IL_0002: call void Program::'<<Main>$>g__f|0_0'(int32&)
Run Code Online (Sandbox Code Playgroud)
当f给 赋值时i,该值存储在调用方法提供的内存地址处:
IL_0000: ldarg.0 // Push argument 0 (= i's address) on the stack
IL_0001: ldc.i4.0 // Push 0 (the value we want to assign) on the stack
IL_0002: stind.i4 // Pop the value and the address from the stack, and store the value at the address
IL_0003: ret
Run Code Online (Sandbox Code Playgroud)