使用多态C#随机化形状

时间:2014-09-23 00:15:34

标签: c# inheritance polymorphism

我正在尝试在我目前正在阅读的C#书中找到的练习。该练习基于继承和多态,并使用Shapes的示例。 这个概念是在GUI中插入一个数字,传入该数字,并在屏幕上显示三种形状的随机组合。

现在,我已经把它带到了每次点击都可以得到随机形状的地方,比如如果传入数字5,我得到5个相同形状的实例。

目标是尝试随机组合三种不同类型的形状,这样如果传入5,则可以获得2个圆形,1个方形和1个斑点圆形。

我已经尝试单步执行调试器,但我无法理解为什么我的Shape方法在我的DrawShapes方法的每次迭代中都没有被调用,并且每次执行时只调用一次。我已经在下面的解决方案中发布了相关代码。任何帮助将不胜感激。感谢。

Canvas类

    public void DrawShapes(int numberOfShapes)
    {
        if (numberOfShapes < 0)
        {
            throw new ArgumentOutOfRangeException();
        }
        var randomVariable = new Random();

        for (var i = 0; i < numberOfShapes; i++)
        {
            var x = randomVariable.Next(0, this.canvas.Width - sizeOfLargestShape);
            var y = randomVariable.Next(0, this.canvas.Height - sizeOfLargestShape);

            this.newShape = new Shape(x, y);
            this.listOfShapes.Add(this.newShape);
        }
    } 

形状类

    private Shape()
    {
        this.randomShape = new RandomShape();
        this.newShapeType = this.randomShape.GetUniqueShape(this);
        this.randomNumber = new Random();
    }

    public Shape(Point location) : this()
    {
        this.point = location;
    }

    public Shape(int x, int y) : this()
    {
        this.point = new Point(x, y);
    }

RandomShape类

    public ShapeType GetUniqueShape(Shape myShape)
    {
        this.square = new SquareShape(myShape);
        this.circle = new CircleShape(myShape);
        this.speckledCircle = new SpeckledCircleShape(myShape);

        this.listOfAllShapeTypes = new List<ShapeType>
        {
           this.square,
           this.circle,
           this.speckledCircle
        };

        this.randomInt = this.myRandom.Next(0, 2);
        return this.listOfAllShapeTypes[this.randomInt];
    }

1 个答案:

答案 0 :(得分:1)

我倾向于这样做:

Shape myShape = null;

switch (myRandom.Next(0, 3))
{
    case 0:
        myShape = new Square();
        break;
    case 1:
        myShape = new Circle();
        break;
    case 2:
        myShape = new SpeckledCircle();
        break;
}

将其放入方法中,并在每次需要随机形状时调用它。