我有一个类:
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/