您可以使用一系列可用项目,例如{ squareType, circleType }。
然后在该数组上随机0..Length 以选择并绘制相关形状。
例如你可以使用这个枚举:
public enum Shapes
{
Circle,
Square
}
并声明这些成员:
static readonly Array ShapesValues = Enum.GetValues(typeof(Shapes));
static readonly int ShapesCount = ShapesValues.Length;
还有这个RNG:
static readonly Random random = new Random();
所以你可以写:
int posX = 0;
do
{
switch ( ShapesValues.GetValue(random.Next(ShapesCount)) )
{
case Shapes.Circle:
// ...
break;
case Shapes.Square:
// ...
break;
default:
throw new NotImplementedException();
}
posX += 50;
}
while ( posX <= Width );
通过这样做,您可以以干净且可维护的方式定义和管理任何必要的形状。
如果形状可以有不同的大小,请考虑使用中间变量来处理。
你也可以这样写来使代码更安全:
static readonly ReadOnlyCollection<Shapes> ShapesValues
= Array.AsReadOnly(Enum.GetValues(typeof(Shapes)).Cast<Shapes>().ToArray());
static readonly int ShapesCount = ShapesValues.Count;
还有:
switch ( ShapesValues[random.Next(ShapesCount)] )