const
is a compile time construct that is guaranteed by the CLI specs to be compiled into the assembly (or for dynamic code into memory) for the Virtual Execution System (VES) to use directly as a literal.
The authoritative source can found in the ECMA-335 Common Language Infrastructure (CLI)
I.8.6.1.2 Location signatures
...
- The literal constraint promises that the value of the location is actually a fixed valueof a built-in type. The value is specified as
part of the constraint. Compilers are required to replace all
references to the location with its value, and the VES therefore need
not allocate space for the location.
...
However, let's not take their word for it.
Unmanaged size
public struct Test1
{
public const long protocolId = 0x41727101980;
public const int action = 0;
public int transactionId;
}
public struct Test2
{
public int transactionId;
}
Usage
Console.WriteLine(Marshal.SizeOf(new Test1()));
Console.WriteLine(Marshal.SizeOf(new Test2()));
Output
4
4
Emitted CIL
Sharp IO
public struct Test1
{
public const long protocolId = 0x41727101980;
public const int action = 0;
public int transactionId;
}
public struct Test2
{
public int transactionId;
}
public void M()
{
Console.WriteLine(Test1.protocolId);
}
Output
public void M()
{
Console.WriteLine(4497486125440L);
}
CIL
IL_0000: ldc.i8 4497486125440
IL_0009: call void [System.Console]System.Console::WriteLine(int64)
IL_000e: ret
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…