Overriding interface method return type with derived class in implementation(在实现中用派生类覆盖接口方法返回类型)
问题描述
我正在尝试在类中实现 (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
{
}
这篇关于在实现中用派生类覆盖接口方法返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在实现中用派生类覆盖接口方法返回类型


基础教程推荐
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01