Overriding interface method return type with derived class in implementation

后端 未结 3 1657
南旧
南旧 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:42

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

    Generics

    interface IFactory where T: BaseCar
    {
        T GetCar();
    }
    
    class MyFactory : IFactory
    {
        MyCar GetCar()
        {
        }
    }
    

    Explicitly implemented members

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

提交回复
热议问题