为一个Base-Sub类创建了多少个实例和引用? [英] How many instances and references are created for a Base-Sub Class?

查看:85
本文介绍了为一个Base-Sub类创建了多少个实例和引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#.NET中,我有2个具体的类。 A类和B类。B类是A类的子类。

In C# .NET, I have 2 concrete classes. Class A and B. Class B is a subclass of Class A.

为以下对象创建了多少个实例(堆上的对象)以及从堆栈到堆对象的引用每行代码:

How many instances (objects on the heap) and references from the stack to the heap objects are created for each line of code:


  1. ClassB b = new ClassB();

ClassA a = new ClassB();


推荐答案

打个比方,该对象是一个气球,引用是一个绑定到气球上​​的字符串,在以下每种情况下,都会有一个Balonlon和一个字符串:

Going with the analogy that the object is a balloon and the reference is a string that is tied to the baloon, in each of the following cases there would be one balolon and one string:

ClassB b = new ClassB(); //one reference, one heap object
ClassA a = new ClassB(); //one reference, one heap object

同时运行这两个对象将创建两个对象和两个对象

Running both at the same time will therefore create two objects and two references.

EDIT 看看由 ClassB 构造函数生成的IL:

EDIT Have a look at this IL generated from ClassB constructor:

.method public hidebysig specialname rtspecialname 
        instance void  .ctor() cil managed
{
  // Code size       7 (0x7)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  call       instance void InheritanceTest.ClassA::.ctor()
  IL_0006:  ret
} // end of method ClassB::.ctor

实例void InheritanceTest.ClassA ::。ctor()表示它调用 ClassA 构造函数作为成员函数(不是作为成员对象上的函数)。这与我对继承类实例发生的情况的理解是一致的,派生类只是基类的所有成员,其后是其自身的成员,类似于C ++。

call instance void InheritanceTest.ClassA::.ctor() indicates that it calls ClassA constructor as a member function(not as a function on a member object). This is in line with my understanding about what happens with instances of inherited classes, that the derived class is simply all the members of the base class, followed by members of its own, similarly to C++.

这篇关于为一个Base-Sub类创建了多少个实例和引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆