Прямоугольник вне класса
Уважаемые! Возникла проблема при выполнении задания на СИ#. У меня стоит задача нарисовать прямоугольник вне основного класса Form. Как мне это сделать? В задании требуется использовать Наследование.
class Geometry
{
Random rand = new Random();
public double thickness;
public int coordinatesX, coordinatesY;
public int R, G, B;
public Geometry(int coordinatesX, int coordinatesY, double thickness ,int R,int G ,int B)
{
coordinatesX = rand.Next(0,100);
coordinatesY = rand.Next(0,100);
thickness = rand.Next(1,10);
this.coordinatesX = coordinatesX;
this.coordinatesY = coordinatesY;
this.thickness = thickness;
this.R = R;
this.G = G;
this.B = B;
}
public void ChangeColor()
{
R = rand.Next(0, 255);
G = rand.Next(0, 255);
B = rand.Next(0, 255);
}
}
class Rectangle1 : Geometry
{
Random rand = new Random();
private int height, widht;
public Rectangle1(int coordinatesX, int coordinatesY, double thickness,int R,int G,int B):base(coordinatesX, coordinatesY, thickness,R,G,B)
{
}
public void PaintRectangle()
{
height = rand.Next(1, 10);
widht = rand.Next(1, 10);
Rectangle Paint = new Rectangle(coordinatesX - widht/2 , coordinatesY + height/2 , coordinatesX + widht/2 , coordinatesY - height/2);
Pen pen = new Pen(Color.Black);
}
Ответы (1 шт):
Автор решения: VoidStack
→ Ссылка
вне основного класса Form - тут же сказано, просто вынеси код за пределы класса формы.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
...
}
...
}
...
class Rectangle1 : Geometry
{
...
}
Если я правильно понял вашу идею о наследовании, то можно так сделать:
public partial class Form1 : Form
{
Rectangle rectangle;
public Form1()
{
InitializeComponent();
rectangle = new Rectangle
{
Location = new Point(100, 100),
Size = new Size(100, 25)
};
pictureBox1.Paint += PictureBox1_Paint;
}
private void PictureBox1_Paint(object sender, PaintEventArgs e)
{
var graph = e.Graphics;
rectangle.Paint(graph);
}
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.Invalidate();
}
}
public abstract class GraphObject
{
public abstract Point Location { get; set; }
public abstract Size Size { get; set; }
public abstract Color Color { get; set; }
public abstract void Paint(Graphics e);
}
public class Rectangle : GraphObject
{
private Point location;
private Size size;
private Color color;
public Rectangle()
{
this.location = new Point(0, 0);
this.size = new Size(0, 0);
this.color = Color.Black;
}
public Rectangle(Point location, Size size, Color? color = null)
{
this.location = location;
this.size = size;
this.color = color == null ? Color.Black : (Color)color;
}
public override Point Location { get => location; set => location = value; }
public override Size Size { get => size; set => size = value; }
public override Color Color { get => color; set => color = value; }
public override void Paint(Graphics e)
{
e.DrawRectangle(new Pen(color), new System.Drawing.Rectangle(location, size));
}
}