简体   繁体   English

在C#中创建派生对象时基本变体的内存分配?

[英]memory allocation of base variabels when derived object is created in c#?

where are member variables of base class stored when an object of derived class is created in c# ? 在c#中创建派生类的对象时,基类的成员变量存储在哪里?

 using System;
 class A
 {
   public int i;
 }
 class B:A
 {
   public int j;
   static public void Main()
   {
       B b = new B();
   }
 }

Here when b object is created where is i variable stored in the heap ?does it store in the instance of the b itself or separately ? 在这里,当创建b对象时,i变量存储在堆中的哪里?它存储在b本身的实例中还是单独存储?

You're creating a single object (on the heap), with all the fields declared in the type hierarchy. 您正在创建单个对象(在堆上),并且所有字段都在类型层次结构中声明。 I believe it's implementation-specific what order they're stored in, but it wouldn't surprise me to see all the fields in the base class, followed by the fields declared in the derived class, etc. (That way the offset for the field for any given declared type would always be the same regardless of the execution-time type.) 我相信它们的存储顺序是特定于实现的,但是让我看到基类中的所有字段,然后是派生类中声明的字段,等等,这并不奇怪。无论执行时间类型如何,任何给定声明类型的字段都将始终相同。)

So the memory layout might look something like: 因此,内存布局可能类似于:

  • Object header / sync block 对象标头/同步块
  • Method table pointer 方法表指针
  • Field i 现场i
  • Field j 栏位j

But to answer the most direct part of your question: all the values that make up the state of the object are stored together, regardless of which type each field is declared in. 但是要回答您问题的最直接部分:构成对象状态的所有值都存储在一起,而不管每个字段声明为哪种类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM