我试图以一种更加灵活的方式来设置我的路标系统,以便可以使用派生类进行更多的自定义,但是我仍然坚持如何设置为它定义派生类型的能力。
我有这样的界面:
public interface ISegment
{
IWaypoint WaypointA { get; set; }
IWaypoint WaypointB { get; set; }
}
我的细分受众群有:
public class Segment : ISegment
{
private Waypoint _waypointA;
public IWaypoint WaypointA
{
get => _waypointA;
set => _waypointA = value;
}
private Waypoint _waypointB;
public IWaypoint WaypointB
{
get => _waypointB;
set => _waypointB = value;
}
}
Waypoint舱:
public class Waypoint : IWaypoint
{
public Vector3 Position {get; set;} // from IWaypoint
//...custom logic ... //
}
Waypoint
是我所有自定义逻辑的派生类。但是我不能这样做,因为它不会将IWaypoint
转换为类型_waypoint
的后备字段Waypoint : IWaypoint
。
什么是正确的设置方式,以便我可以应用自己的自定义航点类,但仍具有接口要求的严格合同设置?
答案 0 :(得分:1)
可能您可以显式实现ISegment
,即:
public class Segment : ISegment
{
public Waypoint WaypointA { get; set; }
IWaypoint ISegment.WaypointA
{
get => WaypointA;
set => WaypointA = (Waypoint) value; // throw an exception if value is not of type Waypoint
}
}
public interface IWaypoint { }
public class Waypoint : IWaypoint { }
public interface ISegment
{
IWaypoint WaypointA { get; set; }
}