一个变量什么时候在c#中赋值



示例:

string input=Console.ReadLine();
Base obj1;
if (input=="a"){
obj1=Derived();
else{
obj1=Base();
}

在这种情况下,我知道一个变量在运行时得到它的值。但是会发生什么当我只有int x=5;时,x什么时候得到它的值,在运行时还是编译时?

您可以(几乎(始终使用IL/JIT ASM进行检查。

对于一个简单的类,例如:

public class C {
public void M() {
var x = 6;
}
}

IL和JIT ASM都用于调试配置,在发行版中,未使用的变量将被删除。

IL:

.method public hidebysig 
instance void M () cil managed 
{
// Method begins at RVA 0x2050
// Code size 4 (0x4)
.maxstack 1
.locals init (
[0] int32 x
)
IL_0000: nop
IL_0001: ldc.i4.6 // Push 6 onto the stack as int32 (0x1C)
IL_0002: stloc.0 // Pop a value from stack into local variable 0 (0x0A)
IL_0003: ret
} // end of method C::M

JIT ASM:

C.M()
L0000: push ebp
L0001: mov ebp, esp
L0003: sub esp, 8
L0006: xor eax, eax
L0008: mov [ebp-8], eax
L000b: mov [ebp-4], ecx
L000e: cmp dword ptr [0x18d0c190], 0
L0015: je short L001c
L0017: call 0x6b214e50
L001c: nop
L001d: mov dword ptr [ebp-8], 6
L0024: nop
L0025: mov esp, ebp
L0027: pop ebp
L0028: ret

因此,正如您所看到的,例如,值6被按原样编译到IL代码中,但对内存中的[x]的赋值发生在运行时。

游戏场地:https://sharplab.io/#v2:C4LghgzgtgNAJiA1AHwAICYCMBYAUKgZgAIMiBhIgbzyNpONQBYiBZACgEoqa7eA3MACciADyIBeIgDYA3D1oBfPAqA=

最新更新