【问题标题】:How can class implement interface with one property also implement other interface类如何实现具有一个属性的接口也实现另一个接口
【发布时间】:2020-05-08 13:24:33
【问题描述】:

抱歉没有明确的标题,这似乎是常见问题,但我找不到任何东西。我需要创建实现如下接口的类,但为什么会出现此错误?是否缺少某些内容,或者无法执行此类操作?

    public class Car : ICar
    {
        public Wheel Wheel { get; set; } //this makes relation in db
    }

    public interface ICar
    {
        IWheel Wheel { get; set; }
    }

    public class Wheel : IWheel
    {

    }

    public interface IWheel
    {

    }

错误:

'Car' does not implement interface member 'ICar.Wheel'. 'Car.Wheel' cannot implement 'ICar.Wheel' because it does not have the matching return type of 'IWheel'.

【问题讨论】:

  • 你的车需要实现 public IWheel Wheel { get;放; }, 不是 public Wheel Wheel { get;放; }
  • ICar 承诺,您可以将set 任何实现IWheel 的东西 实现为Wheel。但是Car 只接受具体的实现Wheel(以及它的子类),没有别的。所以这是(一个)问题。
  • 对不起@auburg,我在你评论后编辑了帖子。我需要 Wheel Wheel,因为它在 db 中创建关系。

标签: c# inheritance interface


【解决方案1】:

从接口显式地实现属性

public class Car : ICar
{
    public Wheel Wheel { get; set; }

    IWheel ICar.Wheel
    {
        get { return Wheel; }
        set { Wheel = (Wheel)value; }
    }
}

这样,您的类的用户将看到输入到成熟的Wheel 类的“原始”Wheel 属性,而使用该接口的人将获得显式实现(在您的情况下,非常直接映射到另一个属性,但在任何情况下,编译器都认为是独立的)。

注意 setter 中的强制转换及其含义,以防接口确实需要具有可写属性。

【讨论】:

  • 我猜看起来有点臭,但它为我完成了这项工作并帮助丢弃了一堆重复的代码。谢谢!
  • @PiotrPiątkiewicz:我不认为在内部调用其他类成员的显式接口实现有什么不好的地方。恕我直言,它有助于保持公共类接口的清洁,并且是对显式接口实现的非常合法的使用。
猜你喜欢
  • 2016-04-28
  • 2022-11-28
  • 2018-07-09
  • 2014-09-16
  • 1970-01-01
  • 2014-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多