简体   繁体   中英

C# Object Hierarchy

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?

  • Should I keep the Parent Cell as an Property in the Station Object?
  • Should I Keep only the Parent Cell Id in the Station Object?
  • Do something differnt?

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.

如果需要从Station导航回到Cell ,则需要Station对象具有一个ParentCell (或Cell )属性,该属性设置为其父单元。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM