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
{
}
这篇关于在实现中用派生类覆盖接口方法返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在实现中用派生类覆盖接口方法返回类型
基础教程推荐
- Moq It.Is<>不匹配 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
