Overriding interface method return type with derived class in implementation

后端 未结 3 1656
南旧
南旧 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.

    0 讨论(0)
  • 2020-12-08 11:31

    Use Generics

    interface IFactory<T> where T: BaseCar
    {
        T GetCar();
    }
    
    class MyFactory : IFactory<MyCar>
    {
        MyCar GetCar()
        {
        }
    }
    
    
    class MyCar : BaseCar
    {
    
    }
    
    0 讨论(0)
  • 2020-12-08 11:42

    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()
        {
        }
    }
    
    0 讨论(0)
提交回复
热议问题