简体   繁体   English

class 如何实现具有一个属性的接口也实现其他接口

[英]How can class implement interface with one property also implement other interface

Sorry for no clear title, It seems like common problem, but I can't find anything.抱歉没有明确的标题,这似乎是常见问题,但我找不到任何东西。 I need to create class that implements interface like below, but why I get this error?我需要创建实现如下接口的 class,但为什么会出现此错误? Is there something missing, or it isn't possible to do things like that?是否缺少某些东西,或者不可能做这样的事情?

    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
    {

    }

Error:错误:

'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'.

Implement the property from the interface explicitly :显式地从接口实现属性:

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

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

That way, users of your class will see the "original" Wheel property typed to the full-fledged Wheel class, whereas whoever uses the interface will get the explicit implementation (that, in your case, quite directly maps to the other property, but is, in any case, considered separate by the compiler).这样,class 的用户将看到输入到成熟的Wheel class 的“原始” Wheel属性,而使用该接口的人将获得显式实现(在您的情况下,它直接映射到另一个属性,但是在任何情况下,编译器都认为是分开的)。

Note the cast in the setter and its implications, in case the interface really needs to have a writeable property.请注意 setter 中的强制转换及其含义,以防接口确实需要具有可写属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM