Üdv, olvastam az Open Close principle elvről, elméletben értem is, de valamiért nem tudom kipróbálni!?
private void button1_Click(object sender, EventArgs e)
{
Rectangle rc = new Rectangle();
rc.Width = 50;
rc.Height = 50;
CombinedAreaCalculator cac = new CombinedAreaCalculator();
cac.Area(); //itt mit kell átadni?
}
public class Rectangle
{
public double Width { get; set; }
public double Height { get; set; }
}
public class CombinedAreaCalculator
{
public double Area(object[] shapes)
{
double area = 0;
foreach (var shape in shapes)
{
if (shape is Rectangle)
{
Rectangle rectangle = (Rectangle)shape;
area += rectangle.Width * rectangle.Height;
}
if (shape is Circle)
{
Circle circle = (Circle)shape;
area += (circle.Radius * circle.Radius) * Math.PI;
}
}
return area;
}
És ezen alapulna az egyszerűsítés, hogy külön osztályokat hozunk létre a különböző alakzatoknak:
public abstract class Shape
{
public abstract double Area();
}
public class Rectangle : Shape
{
public double Width { get; set; }
public double Height { get; set; }
public override double Area()
{
return Width * Height;
}
}
public class Circle : Shape
{
public double Radius { get; set; }
public override double Area()
{
return Radius * Radius * Math.PI;
}
}
public class Triangle : Shape
{
public double Height { get; set; }
public double Width { get; set; }
public override double Area()
{
return Height * Width * 0.5;
}
}
public class CombinedAreaCalculator
{
public double Area(Shape[] shapes)
{
double area = 0;
foreach (var shape in shapes)
{
area += shape.Area();
}
return area;
}
}
Viszont már az első verziót sem tudom használni, mert a gomlenyomás event-be nem tudom meghívni a függvényt! valaki tudna segíteni?










Itt van a kód, részletes magyarázattal: [link]
Nem tudom mi kell még.





"cac.Area(); //itt mit kell átadni?"
Shape tömböt, ahogy láthatod a függvény definícijóában is.
Habár ezt a rakás osztályt az osztályban dolgot nem tudom hogy sikerült összehoznod.





CombinedAreaCalculator cac = new CombinedAreaCalculator();
double area = 0;
Rectangle rc = new Rectangle();
Circle cir = new Circle();
Triangle tri = new Triangle();
rc.Width = 50;
rc.Height = 50;
cir.Radius = 100;
tri.Height = 60;
tri.Width = 90;
//area = cac.Area(); // Itt mit kell átadni?
Shape[] shapes = {rc, cir, tri};
area = cac.Area(shapes); // Itt egy olyan tömböt kell átadni, ami
// olyan objektumokat tartalmaz, amelyeknek az osztálya a Shape
// osztályból van származtatva.
Console.WriteLine("Total area of all shapes: {0}", area);
Kapcsolódó kérdések:
Minden jog fenntartva © 2025, www.gyakorikerdesek.hu
GYIK | Szabályzat | Jogi nyilatkozat | Adatvédelem | Cookie beállítások | WebMinute Kft. | Facebook | Kapcsolat: info(kukac)gyakorikerdesek.hu
Ha kifogással szeretne élni valamely tartalommal kapcsolatban, kérjük jelezze e-mailes elérhetőségünkön!