将 C# Class 投射到他的 child class

Cast a C# Class to his child class

让我们假设这 2 类:

public class ParentClass
{
    public String field1;
    public String field2;
}

public class ChildClass : ParentClass
{
    public String field3;
}

现在,我正在实例化一个 object:

   var c1 = new ParentClass();
   c1.field1 = "aaa";
   c1.field2 = "bbb";

你可以想象这个 object 是由外部函数或另一个 object 提供的。所以我不能改变他的类型。这是一个父类 object。我无法在外部函数中更改他的类型。

我现在要做的是在这个object上“附加”一个field3信息:

   var c2 = c1 as ChildClass;     // c2 is null !
   c2.field3 = "ccc";

我不明白为什么,但 c2 为空。 ChildClass 派生自 ParentClass,所以我不明白为什么强制转换无效。我该怎么办?

非常感谢

A parent 不是 child,因此这个转换是不可能的。要理解这一点,生物学术语通常是最好的:有一个 class Animal 和两个 classes FoxDeer whic hinherit Animal .您不能将 Animal 转换为 Fox,因为它可能是 Deer.

如果你想这样做,我建议你向 child 添加一个构造函数,它从 parent:[=21= 复制 field1field2 ]

public class ChildClass : ParentClass
{
    public ChildClass(ParentClass parent)
    {
       field1 = parent.field1;
       field2 = parent.field2;
    }

    public String field3;
}

你可以这样称呼它:

var c2 = new ChildClass(c1);     
c2.field3 = "ccc";