Overriding interface method return type with derived class in implementation

后端 未结 3 1660
南旧
南旧 2020-12-08 10:59

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 IFacto         


        
3条回答
  •  粉色の甜心
    2020-12-08 11:22

    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.

提交回复
热议问题