c# - 由于 "does not have the matching return type"错误,泛型类型的接口(interface)实现失败

标签 c# generics interface

我有一个类:

 public abstract class Structure<T, S> : IStructure
    where T : StructureModel<S>, new()
    where S : StructureStats, new()
{
    protected T _model;

    public S Stats { get { return _model.Stats; } set { _model.Stats = value; } }

}

和一个界面:

public interface IStructure
{
    StructureStats Stats{ get; set;}
}

代码无法编译,并显示消息

Error 28 'Server.Models.Structures.Structure' does not implement interface member 'Server.Models.Structures.IStructure.Stats'. 'Server.Models.Structures.Structure.Stats' cannot implement 'Server.Models.Structures.IStructure.Stats' because it does not have the matching return type of 'Server.Models.Structures.StructureStats'. C:\SRDevGit\freecon-galactic-server\SRServer\Server.Models\Structures\Structure.cs

我不确定问题是什么; Structure.Stats {get;} 的返回类型应保证与接口(interface)定义匹配,因为泛型类型 S 被定义为从 StructureStats 派生

where S:StructureStats, new()

我错过了什么?如果可能的话,我想避免使 IStructure 通用,因为它会使

的集合变得复杂
<IStructure<GenericType>>

因为 GenericType 是一个多态类。

最佳答案

C# 是强类型的,并且不支持协变返回类型,因此要从 IStructure 继承,Structure 必须返回精确的签名 StructureStats Stats{ get;设置;}。类似 StructureStatsDerived Stats{ get; set;} 不是完全匹配,编译器会拒绝它。

看来您实际上并不需要通用参数 S。您可以删除 S 并仅返回 StructureStats。

关于c# - 由于 "does not have the matching return type"错误,泛型类型的接口(interface)实现失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32280347/

相关文章:

c# - 如果 Eval() != null,ASP.NET Eval() 问题显示两列

typescript - typescript 中的 redux-toolkit createAction() 类型定义

java - spring 框架中 Service 和 DAO 接口(interface)的主要目的是什么?

c# - 如何创建一个通用包装方法来返回包装方法的结果(如果有)?

c# - Newtonsoft TypeNameHandling.all 具有基本命名空间检查安全吗?

c# - CaSTLe Windsor 可以帮我拆分一个大接口(interface)的实现吗?

c# - 输出参数和异常

c# - 查找背包中的元素

c# - 我如何解决错误 "The Process Cannot access the file because it is being used by another process"

c# - 为什么我可以从基于 C#/C++ 中该类型的模板化/泛型类派生