嵌套类中的类的条件实例化

时间:2017-11-01 18:32:08

标签: c# c#-4.0

以下是我想要做的一个例子。

public class Map{
   int id;
   int type;
   List<Points>;
  }

public class Points{
  int xpos;
  int ypos;
  int id;
  //Building bg; or Parking pg;
}

public Building{}
public Parking{}

现在根据Map类中的type属性,我需要在Points类中添加Building或Parking类对象。 例如:如果输入== 1,则在类型== 2添加停车点数时将建筑物添加到其他点。

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

这样做的一种方法是让BuildingParking继承自Point(顺便说一下,我推荐一个更好的名字,也许是Location

public class Location
{
    public int Id { get; }
    public int X { get; }
    public int Y { get; }
}

public class Building : Location
{
    public int Stories { get; }
}

public class Parking: Location
{
    public int Capacity { get; }
}

现在,List<Location>内部Map可以处理建筑物和停车场:

locations.Add(someBuilding);
locations.Add(someParking);

另一个选择是使用接口:interface ILocation将由BuildingParking以及List<ILocation> Map实施。

何时使用一个或另一个取决于不同类型之间的共同点是什么:

  • 继承:派生类型基类, dog 动物
  • 接口:实现接口的类型与接口类似int 的行为就像IEquatable<int>string一样。除了这种行为之外,stringint之间是否有任何共同点?
相关问题