Reputation: 1532
I have a List of Cells and each List has a List of Stations.
Sometimes I need to get the Parent Cell of a Station.
How would I implement this hierarchy?
Upvotes: 1
Views: 2478
Reputation: 9123
If you want a different answer, there is a way you can implement the hierarchy without actual composition. Create a station object where each method accepts Cell as a parameter, for example:
public void DoStuff(whatever x, Cell parent)
{
}
Each station will be evaluated in the context of its parent cell, but you can use the same Station
object to represent different stations in the hierarchy.
This solution is provided for the sake of variety. In most cases, the way to go is composition, as suggested above. Also, I think you should use the Cell itself, rather than an Id to it.
Upvotes: 1
Reputation: 5340
If I were you, I would create two classes:
public class Cell {
...
public List<Station> Stations {
get {...}
}
protected Station AddStation() {
Station result = new Station(this);
Stations.Add(result);
return result;
}
}
public class Station {
public Station(Cell cell) {
this.cell = cell;
}
Cell cell;
public Cell Cell {get {return cell;}}
}
Having this structure, you can always access the Cell from the Station object.
Upvotes: 5
Reputation: 499132
If you need to navigate back from Station
to Cell
, you need the Station
object to have a ParentCell
(or Cell
) property that is set to its parent cell.
Upvotes: 2