I am wondering why this populates the derived class appropriately:
BaseClass bc = MethodThatReturnsBaseClassObject();
DerivedClass dc = bc as DerivedClass;
But this creates a null derived class object:
DerivedClass dc = MethodThatReturnsBaseClassObject() as DerivedClass;
This happens because BaseClass
is not an instance of DerivedClass
(but DerivedClass
is an instance of BaseClass
), so you cannot cast an instance of the base class as an instance of the derived class (well, you can, but it will be null as you have found).
You can do what (I think) you are trying to achieve by adding a constructor to the derived class that takes in the base class as a parameter:
public DerivedClass(BaseClass baseClass) {
// Populate common properties, call other derived class constructor, or call base constructor
}
Then:
DerivedClass dc = new DerivedClass(MethodThatReturnsBaseClassObject());
It is hard to tell without seeing what is coming out of MethodThatReturnsBaseClassObject();
.
There is absolutely no difference between your statements (if MethodThatReturnsBaseClassObject();
always returns DerivedClass
object) other than temporary assignment to BaseClass
in first case.
If MethodThatReturnsBaseClassObject()
returns instance of BaseClass
dc will always be null. BaseClass
will hold a reference in this case.
If MethodThatReturnsBaseClassObject()
returns instance of DerivedClass
dc will have reference (and will not be null).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.