【问题标题】:Interfaces with type override C#具有类型覆盖 C# 的接口
【发布时间】:2023-03-08 10:15:01
【问题描述】:

我正在尝试以更灵活的方式设置我的航点系统,以便我可以使用派生类进行更多自定义,但我不知道如何设置为它定义派生类型的能力。

我有这样的界面:

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;
    }
}

航点类:

public class Waypoint : IWaypoint 
{

     public Vector3 Position {get; set;} // from IWaypoint

     //...custom logic ... //
}

Waypoint 是我所有自定义逻辑的派生类。但是我不能这样做,因为它不会将IWaypoint 转换为Waypoint : IWaypoint 类型的支持字段_waypoint

设置这个的正确方法是什么,以便我可以应用我自己的自定义航点类,但仍然具有接口要求的严格合同设置?

【问题讨论】:

  • Segment 内部是否依赖于具体的实现 Waypoint 还是仅依赖于其实现 IWaypoint 的航路点?
  • Segment 只有 IWaypoint 实现,否则它将迫使我只使用特定的 Waypoint 类。
  • 那么到底是什么不起作用?你能举个例子吗?
  • @KirillPolishchuk Segment 中的设置器在语法上是错误的,因为它无法将 IWaypoint 转换为 Waypoint。
  • 你能把_waypointA的数据类型改成IWaypoint吗?

标签: c# .net types interface


【解决方案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; }
}

【讨论】:

  • 当属性类型为IWaypoint 时,为什么这允许您将value 转换为Waypoint
  • @WDUK,这不是转换,这是强制转换。为什么不应该?
猜你喜欢
  • 2018-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-25
  • 1970-01-01
相关资源
最近更新 更多