我想知道为什么这会适本地填充派生类:

BaseClass bc = MethodThatReturnsBaseClassObject();
DerivedClass dc = bc as DerivedClass;

但这会创建一个空的派生类对象:
DerivedClass dc = MethodThatReturnsBaseClassObject() as DerivedClass;

最佳答案

发生这种情况是因为BaseClass不是DerivedClass的实例(但是DerivedClassBaseClass的实例),所以您不能将基类的实例转换为派生类的实例(可以,但是,它会为null)已经发现)。

您可以通过将构造函数添加到将基类作为参数的派生类中来实现您想达到的目的(我认为):

public DerivedClass(BaseClass baseClass) {
    // Populate common properties, call other derived class constructor, or call base constructor
}

然后:
 DerivedClass dc = new DerivedClass(MethodThatReturnsBaseClassObject());

关于c# - 将基类转换为派生类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19800878/

10-11 11:45