Βασικά υπάρχει άλλος τρόπος, να αλλάξεις τα arguments του constructor σε Points[] ώστε να παίρνει τα σημεία του κάθε σχήματος και να αρχικοποιεί.
Εκανα και άλλες δύο τάξεις οι οποίες κληρονομούν το Shape2d (Square , Hexagon) και επικάλυψα τη μεθοδο ToString() του Shape2D και την καλώ μέσα από το δομητή για να φαίνεται στην κονσόλα τα σημεία που είναι αποθηκευμένα για κάθε σχήμα. Υπαρχει τρόπος να δωσεις παραμετροποιημένες τιμές μέσω κάποιας μεταβλητής όταν καλείς τη base class ή χρήση των μεθόδων για ορισμό των τιμών είναι αναπόφευκτη.
διορθωμένο το παραπάνω παράδειγμα το οποίο δε δούλευε γιατί δεν είχα ορίσει τον πίνακα Points σε αντικείμενο
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | using System; using System.Collections.Generic; using System.Linq; using System.Text;
namespace Inheritance { class Program { static void Main(string[] args) { Circle c = new Circle(2, new Point(10, 2)); Square s = new Square(); Hexagon h = new Hexagon(); Console.WriteLine("Press any key to continue"); Console.ReadKey(); } } class Hexagon : Shape2D { public Hexagon(): base(new Point[] { new Point(0, 0), new Point(0, 0), new Point(0, 0), new Point(0, 0),new Point(0, 0), new Point(0, 0) }) {
} } class Square : Shape2D { public Square() :base(new Point[]{new Point(0,0),new Point(0,0),new Point(0,0),new Point(0,0)}) {
}
} class Circle :Shape2D { private int _radius; private Point _center; public int Radius { get { return _radius; } set { _radius = value; } } public Point Center { get { return _center; } set { _center = value; } }
public Circle(int radius,Point center):base(new Point[]{new Point(0,0)}) { _center = center; _radius = radius; } } class Point { private int _x; private int _y; //constructor public Point(int x,int y) { _x = x; _y = y; } public int X { get { return _x; } set { _x= value; } } public int Y { get { return _y; } set { _y = value; } }
public override string ToString() { return "[x="+_x+"] ,[y="+_y+"]"; } } class Shape2D : Point { private Point[] _points; //constructor public Shape2D(Point[] points):base(1,1) { _points = new Point[points.Length]; for (int p=0; p < points.Length;p++ ) { Random r = new Random(100); _points[p] = new Point(points[p].X,points[p].Y); } Console.WriteLine(ToString()); }
public override string ToString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < _points.Length; i++) { sb.AppendLine("[x = " + _points .X + " ,y = " + _points .Y + "]"); } return sb.ToString(); } } } |