问题
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:
ClassB b = new ClassB();
ClassA a = new ClassB();
回答1:
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 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
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++.
回答2:
It really depends on what members are in each class. Supposing they are empty classes, one reference per object, for a total of two. That is, creating a ClassB
object does not create references to any more than itself.
If they have members, of course, there are additional references for the members, but I think that is not the gist of your question.
回答3:
IN the first case - you will have only one instance of class B. In the second case, you will have one instance of class B. The instance of class A will not be created in the second case.
来源:https://stackoverflow.com/questions/3359349/how-many-instances-and-references-are-created-for-a-base-sub-class