OOP C#问题:制作水果梨

Ada*_*ane 4 .net c# oop

鉴于我有一个设置了一些属性的Fruit实例,并且我想将这些属性放入一个新的Pear实例中(因为这个特殊的Fruit恰好具有梨的特性),实现这种效果的最佳方法是什么?

例如,我们不能做的只是简单地将水果浇到梨上,因为不是所有的水果都是梨:

public static class PearGenerator {
    public static Pear CreatePear () {

        // Make a new generic fruit.
        Fruit genericFruit = new Fruit();

        // Upcast it to a pear. (Throws exception: Can't cast a Fruit to a Pear.)
        Pear pear = (Pear)genericFruit;

        // Return freshly grown pear.
        return ( pear );
    }
}

public class Fruit {
    // some code
}

public class Pear : Fruit {

    public void PutInPie () {
        // some code
    }

}
Run Code Online (Sandbox Code Playgroud)

谢谢!

更新:

我不控制"新的Fruit()"代码.我的出发点是,我有一个水果可以合作.我需要以某种方式将水果变成新梨.也许一个一个地复制所有的属性?

EMP*_*EMP 15

Because the Fruit you've created isn't a Pear!


Edit: If you already have a Fruit and need to create a Pear from it then yes, you have no choice but to copy all the properties to a new Pear object. This should ideally be done inside a Pear constructor that you create especially for that purpose.


Alu*_*ord 13

它不是梨.尝试更换你的线路

Fruit genericFruit = new Fruit();
Run Code Online (Sandbox Code Playgroud)

有:

Fruit genericFruit = new Pear();
Run Code Online (Sandbox Code Playgroud)


mdm*_*dma 5

沮丧的失败,因为创建的实例是Fruit,使之成为Pear,更改代码以

    // Make a Pear - it looks like a fruit, tastes like a fruit,
    // and quacks like a fruit. It must be a fruit.
    Fruit genericFruit = new Pear();

    // Downcast it to a pear. 
    Pear pear = (Pear)genericFruit;
Run Code Online (Sandbox Code Playgroud)

向下看看实际的类型,而不是声明的类型 - 但你不知道实际的类型是什么(除非你使用is/as测试).这就是为什么它有点危险,大多数人试图尽可能避免向下倾斜.

编辑:要将水果制成梨,您可以自己创建一个新的梨,并尽可能地初始化它.所有水果共有的一些特性可以被复制,从水果到梨.但它也可能就像试图将一个方形钉子放入一个圆孔中,混合你的隐喻并最终得到果泥.