在实现中用派生类覆盖接口方法返回类型 [英] Overriding interface method return type with derived class in implementation

查看:33
本文介绍了在实现中用派生类覆盖接口方法返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在类中实现 (C#) 接口方法,返回派生类型而不是接口中定义的基类型:

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()
    {
    }
}

当然是在哪里:

class MyCar : BaseCar
{

}

但是,会发生以下错误:

However, the following error happens:

MyFactory"没有实现接口成员IFactory.GetCar()".'MyFactory.BaseCar()' 无法实现 IFactory.GetCar()',因为它没有匹配的返回类型 'BaseCar'.

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

推荐答案

使用泛型

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

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


class MyCar : BaseCar
{

}

这篇关于在实现中用派生类覆盖接口方法返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆