Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

.net core - Why having const fields in structs change its size in memory. C#


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...