我有两个形状列表 - 矩形和圆形.它们共享3个共同属性 - ID,类型和边界
圆圈有2个额外的属性 - 范围和中心
如何将每种类型的列表连接到一个列表中,以便我可以迭代它们,这样我就不必键入两个foreach周期
这可能比组合清单更好吗?
public interface IRectangle
{
string Id { get; set; }
GeoLocationTypes Type { get; set; }
Bounds Bounds { get; set; }
}
public class Rectangle : IRectangle
{
public string Id { get; set; }
public GeoLocationTypes Type { get; set; }
public Bounds Bounds { get; set; }
}
public interface ICircle
{
string Id { get; set; }
GeoLocationTypes Type { get; set; }
Bounds Bounds { get; set; }
float Radius { get; set; }
Coordinates Center { get; set; }
}
public class Circle : ICircle
{
public string Id { get; set; }
public GeoLocationTypes Type { get; set; }
public Bounds Bounds { get; set; }
public float Radius { get; set; }
public Coordinates Center { get; set; }
}
public class Bounds
{
public Coordinates NE { get; set; }
public Coordinates SW { get; set; }
}
public class Coordinates
{
public float Lat { get; set; }
public float Lng { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
同时创建IRectangle并ICircle继承共享类型 - 比如说IShape.
一List<IShape>则可以采取任何IRectangle和ICircle类型及其继承类型.
由于两个IRectangle和ICircle共享大量属性,你可以这样做:
public interface IShape
{
string Id { get; set; }
GeoLocationTypes Type { get; set; }
Bounds Bounds { get; set; }
}
public interface ICircle : IShape
{
float Radius { get; set; }
Coordinates Center { get; set; }
}
public interface IRectangle : IShape
{
}
Run Code Online (Sandbox Code Playgroud)
创建一个IShape包含公共属性的接口,然后实现它以及ICircle和IRectangle.(您还可以使用具有该属性的基类).
您应该能够加入圆和矩形列表以获取IShapes列表.