Where does the memory is allocated for static,constant and readonly fields?

会有一股神秘感。 提交于 2021-02-16 13:23:21

问题


I have used the three fields in the program and got the difference in usage but I am little confused where does these fields are getting stored? either in data segment(stack or heap?) or code segment?

static int a;
const int b=1235;
readonly int c;

in ILDASM the the fields are described as the following

for static: .field private static int32 a

for constant: .field private static literal int32 b = int32(0x000004D3)

for readonly: .field private initonly int32 c


回答1:


As you know const is static which means it is stored in the heap. Readonly is just like a member. Just like any other member the value of the readonly also gets stored on the heap. For any furthur reference about const and readonly refer the link below. https://blogs.msdn.microsoft.com/csharpfaq/2004/12/03/what-is-the-difference-between-const-and-static-readonly/




回答2:


Every static variable is stored on the heap, regardless of whether it's declared within a reference type or a value type. There is only one slot in total no matter how many instances are created. (There don't need to be any instances created for that one slot to exist though.) The details of exactly which heap the variables live on are complicated. more info you can find HERE




回答3:


CLR is the basic and Virtual Machine component of the .NET Framework. It is the run-time enviornment in the .NET Framework that runs the codes and helps in making the development process easier by providing the various services. The CLR divides the memory into three distinct regions: the stack, the heap, and the high frequency heap. Static objects need to survive a GC collection and are stored in the high frequency heap. Static and constants objects are stored in the loader heap as they exist in the memory throughout the lifetime of the application; they don't need to be garbage collected.



来源:https://stackoverflow.com/questions/54105028/where-does-the-memory-is-allocated-for-static-constant-and-readonly-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!