Overriding interface method return type with derived class in implementation

混江龙づ霸主 提交于 2019-12-17 17:56:12

问题


I am trying to implement (C#) an interface method in a class, returning a derived type instead of the base type as defined in the interface:

interface IFactory
{
    BaseCar GetCar();
}

class MyFactory : IFactory
{
    MyCar GetCar()
    {
    }
}

Where, of course:

class MyCar : BaseCar
{

}

However, the following error happens:

'MyFactory' does not implement interface member 'IFactory.GetCar()'. 'MyFactory.BaseCar()' cannot implement IFactory.GetCar()' because it does not have the matching return type of 'BaseCar'.

Can anyone point me as to why this fails, and how would be the best way to work around it?


回答1:


Use Generics

interface IFactory<T> where T: BaseCar
{
    T GetCar();
}

class MyFactory : IFactory<MyCar>
{
    MyCar GetCar()
    {
    }
}


class MyCar : BaseCar
{

}



回答2:


There are 2 ways to accomplish this. You can either use generics or explicitly implement interface members.

Generics

interface IFactory<T> where T: BaseCar
{
    T GetCar();
}

class MyFactory : IFactory<MyCar>
{
    MyCar GetCar()
    {
    }
}

Explicitly implemented members

interface IFactory
{
    BaseCar GetCar();
}

class MyFactory : IFactory
{
    BaseCar IFactory.GetCar()
    {
        return GetCar();
    }

    MyCar GetCar()
    {
    }
}



回答3:


Your GetCar method has to return a BaseCar in order to implement the interface. As the error says, the class' method's return type must match the interface's method's return type.

There's nothing stopping you creating an instance of MyCar, then returning that:

BaseCar GetCar()
{
    return new MyCar();
}

An alternative, if you want to get the typed version of the new class, is to use generics as per John's answer.



来源:https://stackoverflow.com/questions/8564593/overriding-interface-method-return-type-with-derived-class-in-implementation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!