简体   繁体   English

C#中继承对象的内存分配

[英]Memory allocation for object in inheritance in C#

I'm confused about how object allocation is done in the case of inheritance consider the following code. 我对在继承的情况下如何完成对象分配感到困惑,请考虑以下代码。

class Base
{
}
class Derived : Base
{
// some code
}

and from main if we do 如果我们这样做,从主要

Derived d = new Derived();

and

Base b = new Derived();

what is the memory allocation of both cases in the heap. 堆中两种情况的内存分配是什么。 Is the derived object in inside base object or they both are beside each other 派生对象是在基础对象内部还是它们彼此相邻

Memory allocation for both objects will look exactly the same. 两个对象的内存分配看起来完全相同。 Both objects are of the same type Derived . 两个对象都是Derived相同的类型。

Of course, each object will be allocated in its own space on the heap. 当然,每个对象都将在堆上的自己的空间中分配。

What counts when creating objects is the class (type) used to construct the object, not the type of reference where object will be stored. 创建对象时的重要性是用于构造对象的类(类型),而不是存储对象的引用类型。

Each object exists as complete entity, but you can look at it as summary of all parts from all the classes it inherits from. 每个对象都作为完整实体存在,但您可以将其视为从其继承的所有类中的所有部分的摘要。 In a way Derived object instance contains Base object instance inside. 在某种程度上, Derived对象实例包含Base对象实例。 Not the other way around. 不是相反。

In both cases you instanciate objects of the concrete Derived class, so the memory footprint would be the same for both - you refer to them using references of the Base and the Derived class, but you instantiate the Derived class in both cades. 在这两种情况下,您都会实例化具体Derived类的对象,因此两者的内存占用量相同 - 您使用Base和Derived类的引用来引用它们,但是您可以在两个cades中实例化Derived类。

But as to providing a general answer to your question - yes, in memory instances of derived classes contain all the members of their base classes. 但是,为您的问题提供一般答案 - 是的,在派生类的内存实例中包含其基类的所有成员。

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

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