我有如下的基类和派生类(这只是一个例子):
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)
}
}
Derived_TripLog构造函数使用基本构造函数加载路标文件。派生类中的旅行自然仍然是空的。我打算将base.trips复制到派生行程中。
两个问题:
是复制处理这种情况的标准方法吗?如果基层Trip类有很多成员和集合,那么复制所有成员可能会很痛苦。
如果复制是标准方法,那么我实质上将内存使用量增加了一倍。(base.trips可能会很大。)似乎我可以只做base.trips.Clear()来释放这些资源。是否有正确的方法?
这就是泛型的用途。您不必在每个子类中都有不同类型的行程列表,而只需在基类中包含一个具有通用类型的列表:
class Base_TripLog<TripType> where TripType: Base_Trip {
public List<TripType> trips = ...
public Base_TripLog(string log_filename) {
// load stuff into trips
}
}
现在,您可以使用正确的泛型参数继承此类:
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
}
}
这样,您无需为每个类都重新声明属性,而只需对派生自的所有类型进行单个定义Base_Trip
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句