将多个值+名称存储在一个对象中

时间:2016-12-12 17:34:50

标签: c#

我想绘制多个圆圈 - 不要随意重叠。为此我想创建一个对象来存储圆半径和x和y位置(那些是随机的)。然后我想将这些对象添加到数组,以便稍后计算圆是否与任何其他圆重叠。

我知道在p5.js中,Javascript的代码如下所示:

var circles = [];
for (var i = 0; i < 30; i++) {
  var circle = {
    x: random(width),
    y: random(height),
    r: 32
  };
  circles.push(circle);
}

//and now I can draw the circles like following but in a loop:

ellipse(circles[i].x, circles[i].y, circles[i].r*2, circles[i].r*2);

有没有办法在C#中执行此操作?

2 个答案:

答案 0 :(得分:2)

做这样的事情:

public class Circle
    {
        // In C# this is called a "property" - you can get or set its values
        public double x { get; set; }

        public double y { get; set; }

        public double r { get; set; }
    }

    private static List<Circle> InitializeList()
    {
        Random random = new Random();

        List<Circle> listOfCircles = new List<Circle>();

        for (int i = 0; i < 30; i++)
        {
            // This is a special syntax that allows you to create an object
            // and initialize it at the same time
            // You could also create a custom constructor in Circle to achieve this
            Circle newCircle = new Circle()
            {
                x = random.NextDouble(),
                y = random.NextDouble(),
                r = random.NextDouble()
            };

            listOfCircles.Add(newCircle);
        }

        return listOfCircles;
    }

在屏幕上实际绘制它的逻辑将取决于您是否正在执行Windows窗体,ASP.NET,WPF或其他任何操作,但您可以执行以下操作:

 foreach (Circle circle in InitializeList())
 {
     // This'll vary depending on what your UI is
     DrawCircleOnScreen(circle);
 }

答案 1 :(得分:1)

class Circle {
    public double Radius { get; set; }
    public Vector2 Position { get; set; }
}

class Vector2 {
    public double X { get; set; }
    public double Y { get; set; }
}

阅读C#课程。