0
我正在尝试在C#书中发现的练习上工作,我目前正在审阅。该练习基于继承和多态性并使用Shapes的例子。 这个概念是在GUI中插入一个数字,该数字被传入,并且三个形状的随机组合将出现在屏幕上。多态C随机化形状#
现在,我已经知道每次点击时都可以得到随机形状,例如,如果传入数字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);
}
}
Shape类
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];
}
我不知道你得到的输出,但'GetUniqueShape'完全不能返回'speckledCircle',因为'Next'方法是排他性的。 – Mephy 2014-09-23 00:20:09
哦。我认为下一步将成为三个元素[0,1,2]的列表索引。我会切换它并尝试它。 – Ashton 2014-09-23 01:56:38