简体   繁体   English

将基类转换为派生类

[英]Convert a base class to a derived class

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: 但是这会创建一个null派生类对象:

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). 发生这种情况是因为BaseClass不是DerivedClass的实例(但是DerivedClassBaseClass一个实例),所以你不能将基类的实例DerivedClass为派生类的实例(嗯,你可以,但它会为null,因为你找到)。

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(); 如果没有看到MethodThatReturnsBaseClassObject();很难分辨MethodThatReturnsBaseClassObject(); .

There is absolutely no difference between your statements (if MethodThatReturnsBaseClassObject(); always returns DerivedClass object) other than temporary assignment to BaseClass in first case. 在第一种情况下,除了临时赋值给BaseClass之外,你的语句(如果MethodThatReturnsBaseClassObject();总是返回DerivedClass对象)之间绝对没有区别。

If MethodThatReturnsBaseClassObject() returns instance of BaseClass dc will always be null. 如果MethodThatReturnsBaseClassObject()返回BaseClass实例,则dc将始终为null。 BaseClass will hold a reference in this case. 在这种情况下, BaseClass将保留一个引用。

If MethodThatReturnsBaseClassObject() returns instance of DerivedClass dc will have reference (and will not be null). 如果MethodThatReturnsBaseClassObject()返回DerivedClass实例,dc将具有引用(并且不会为null)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM