gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:41:30 25 4
gpt4 key购买 nike

我有一个类:

 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; } }

}

和一个接口(interface):

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com