Inheritance base class reference C#
class Base
{
//...
public int i = 5;
}
class Drifted : Base
{
//...
public int b = 10;
}
Base ObjectOrReference = new Drifted();
So Base ObjectOrReference;
is reference to the 开发者_开发百科base type.
When we write Base ObjectOrReference = new Drifted();
it becomes object because by using 'new' we allocate memory for it? Or it still reference and if it is true, what type does it have?
Direct question is: "Is ObjectOrReference
object?"
It's still a reference, a pointer to the object on the heap. It is of type Drifted
.
Even though your reference is of the Base
type, the underlying object is Drifted
and any overridden members in the derived class Drifted
will be used instead of those on Base
, even though you are trying to use Base
.
In the case of member hiding using the new
syntax, if you have a reference to the base type it will bypass any derived classes that are hiding the members.
An overview can be found online with Googling for "C# Reference Types". I skimmed this, looks like a worthwhile read:
http://www.albahari.com/valuevsreftypes.aspx
Base ObjectOrReference = new Drifted();
with that, you have created a Drifted
instance but is referenced by Base
reference variable ObjectOrReference
. Right now it's capabilities are limited to that of what's available in Base
. If you want to, say access int b
in Drifted
, you'll have to cast it to Drifted
Yes, ObjectOrReference
is an object and a valid object.
It is an object of Drifted
Type. It is a basic concept of Object Oriented Programming that pointer/ref of base class(ObjectOrReference
in your case) can hold/refer to object of it's derived classes(Drifted
in your case) thats why it is not an error and a valid object of Drifted
type
It is and always be a reference. Think of object variables as pointers/refernces. While the actual object creation/allocation happens on heap, references are created on local stack space.
You have instantiated the object of a derived class but are refering to its memory location through its base class reference type (ObjectOrReference). Object reference knows the member of its type only (i.e with in its base class) and is completely unaware about the member of its derived class. So you can't access the member of an derived class and you can't type cast here as we are talking about inheritance
精彩评论