Reputation: 303
i've got base and derived classes as follows (this is just an example):
class Base_TripLog {
public List<Base_Trip> trips = ...
public Base_TripLog(string log_filename) {
// load stuff into trips
}
}
class Base_Trip {
public string vehicle_id = ...;
public Dictionary<ulong, Base_Waypoint> waypoints = ...
public Base_Trip() {
}
public add_waypoint(ulong epoch_sec, Base_Waypoint waypoint) {
waypoints.Add(epoch_sec, waypoint);
}
}
class Base_Waypoint {
/// time and gps coords
}
class Derived_TripLog : Base_TripLog {
public string company_name;
public new List<Derived_Trip> trips = ...
public Derived_TripLog(string company_name, string filename) : base(filename) {
this.company_name = company_name;
if (trips.Count > 0) {
// do stuff
}
}
}
class Derived_Trip : Base_Trip {
public int duration_sec;
public Derived_Trip() : base() {
duration = compute_trip_duration(waypoints)
}
}
the Derived_TripLog constructor uses the base constructor to load the file of waypoints. trips in the derived class will naturally still be empty. i was planning to copy base.trips into the derived trips.
two question:
is copying the standard way to handle this situation? if the base Trip class had lots of members and collections, it could be it pain to copy all the members.
if copying is the standard approach, then i'm essentially doubling memory usage. (base.trips can be quite large.) it seems i could just do base.trips.Clear() to free up those resources. if there a correct way?
Upvotes: 1
Views: 223
Reputation: 37050
That´s what generics are for. Instead of having a list of trips of different types in every child-class, you have a single list with the generic type within your base-class:
class Base_TripLog<TripType> where TripType: Base_Trip {
public List<TripType> trips = ...
public Base_TripLog(string log_filename) {
// load stuff into trips
}
}
Now you can just inherit this class using the correct generic argument:
class Derived_TripLog : Base_TripLog<Derived_Trip>
{
public string company_name;
public Derived_TripLog(string company_name, string filename) : base(filename)
{
this.company_name = company_name;
if (trips.Count > 0) {
// do stuff
}
}
This way you don´t need to re-declare the property for every class, but just have a single definition for all types that derive from Base_Trip
.
Upvotes: 1