当我想以随机方式显示我的对象时,我陷入了困境。 假设我得到了这个面板,假设矩形和椭圆是对象
我需要做什么才能让它们以这种形式显示。
我需要使用Random n = new Random
吗?或者还有其他方法。
这是我的尝试之一,但我不知道如何集成随机函数来显示它们。
do
{
dr.DrawEllipse(Bpen, i + 30, 25, i + 30, 25);
i += 50;
}
while (i <= this.Width);
最佳答案
您可以使用一系列可用项目,例如 { 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)] )
关于c# - 如何使用循环随机选择一个形状来绘制多个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65551584/