About casting and objects
开发者_如何转开发it's simple, i just want a explanation about this:
internal class B { // Base class
}
internal class D : B { // Derived class
}
in other class I wrote:
B b3 = new Object(); //compilation time error!
why??? We suposse that all classes inherit from "object"
B
is more specialized than Object
, therefore you cannot assign an Object
instance to a B
reference. This is because not every Object
is actually a B
- only the opposite is true.
Let's assume that you have a field x
in the class B
. When you instantiate an Object
, no memory is reserved for this field, and if you could assign it to a reference of type B
, it would therefore try to read or write to unallocated memory, which is not allowed (or useful).
All classes are object
s, but not all objects are {someclass}
.
In a similar way, all buses are vehicles, but not all vehicles are buses.
精彩评论