How does .net managed memory handle value types inside objects?

前端 未结 6 1839
[愿得一人]
[愿得一人] 2021-01-18 21:42
public class MyClass
{
    public int Age;
    public int ID;
}

public void MyMethod() 
{
    MyClass m = new MyClass();
    int newID;
}

To my un

6条回答
  •  后悔当初
    2021-01-18 22:13

    A variable or other storage location of a structure type is an aggregation of that type's public and private instance fields. Given

    struct Foo {public int x,y; int z;}
    

    a declaration Foo bar; will cause bar.x, bar.y, and bar.z to be stored wherever bar is going to be stored. Adding such a declaration of bar to a class will, from a storage-layout perspective, be equivalent to adding three int fields. Indeed, if one never did anything with bar except access its fields, the fields of bar would behave the same as would three fields bar_x, bar_y, and bar_cantaccessthis_z [accessing the last one would require doing things with bar other than accessing its fields, but it would take up space whether or not it's ever actually used for anything].

    Recognizing structure-type storage locations as being aggregations of fields is the first step to understanding structures. Trying to view them as holding some kind of object might seem "simpler", but doesn't match how they actually work.

提交回复
热议问题