多态性C#随机形状
本文关键字:随机 多态性 | 更新日期: 2023-09-27 18:23:55
我正在努力做一个在C#书中找到的练习。该练习以继承和多态性为基础,并以Shapes为例。这个概念是在GUI中插入一个数字,这个数字被输入,三个形状的随机组合将出现在屏幕上。
现在,我已经达到了每次点击都可以获得随机形状的程度,比如说,如果输入数字5,我会得到5个相同形状的实例。
目标是尝试获得三种不同类型形状的随机组合,这样,如果传入5,您可能会得到2个圆、1个正方形和1个斑点圆。
我已经尝试过调试程序,但我很难理解为什么在DrawShapes方法的每次迭代中都没有调用我的Shape方法,而每次执行只调用一次。我已经在下面发布了我的解决方案中的相关代码。如有任何帮助,我们将不胜感激。谢谢
画布类
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);
}
随机形状类
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];
}
我倾向于这样做:
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;
}
把它放在一个方法中,每次需要一个随机形状时都调用它。