With the structure..
abstract class Unit
{
int Id;
}
class Measure : Unit
{
int Current;
int Baseline;
}
class Weight : Unit
{
int Minimum;
int Maximum;
int Current;
}
I basically want to add an “Add” method for adding, say, two Measures together, or adding two Weights together. But it needs to be in the Unit base class. So basically if I had
List<Units> units = new List<Unit>();
List<Units> otherUnits = new List<Unit>();
// populate units with various Measures and Weights.
// populate otherUnits with various Measures and Weights.
foreach(Unit u in units)
{
u.Add(
// add something from the otherUnits collection. Typesafe, etc.
);
}
I have tried ..
public abstract T Add<T>(T unit) where T : Unit;
in the Unit class, but I get errors about how it isn’t an appropriate identifier in the inherited classes when I try to fill “T” with the appropriate class. Any ideas?
You need to change your
Unitabstract class to take a generic type:Then you can add the
Addabstract method:So your measurement and weight classes will now look like:
Alternatively, add the following abstract method to
Unit:And then you’ll need to constraint this using type checking within your inheriting class: