[英]Interface design implementation error: … cannot implement … because it does not have a matching return type
[英]Interface implementation fails for generic type, because of “does not have the matching return type” error
我有一堂课:
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;}
}
代码无法编译,并显示以下消息
错误28'Server.Models.Structures.Structure'未实现接口成员'Server.Models.Structures.IStructure.Stats'。 “ Server.Models.Structures.StructureStats”无法实现“ Server.Models.Structures.IStructure.Stats”,因为它没有匹配的“ Server.Models.Structures.StructureStats”返回类型。 C:\\ SRDevGit \\ freecon星系服务器\\ SRServer \\ Server.Models \\结构\\ Structure.cs
我不确定是什么问题; 应该保证Structure.Stats {get;}的返回类型与接口定义匹配,因为通用类型S被定义为通过以下方式从StructureStats派生
where S:StructureStats, new()
我想念什么? 如果可能的话,我想避免使IStructure通用,因为它会使
<IStructure<GenericType>>
因为GenericType是一个多态类。
C# 是强类型的,并且不支持协变返回类型,因此要从IStructure继承,Structure必须返回确切的签名StructureStats Stats{ get; set;}
StructureStats Stats{ get; set;}
。 类似于StructureStatsDerived Stats{ get; set;}
StructureStatsDerived Stats{ get; set;}
不是完全匹配项,编译器会拒绝它。
看起来您实际上并不需要通用参数S。您可以删除S并仅返回StructureStats。
没有使用通用接口就无法实现它,您还需要在通用约束中切换Structure<T, S>
的顺序
public class Structure< T, S> : IStructure<S>
where S : StructureStats, new()
where T : StructureModel<S>, new()
{
protected T _model;
public S Stats { get { return _model.Stats; } set { _model.Stats = value; } }
}
public interface IStructure<S> where S : StructureStats
{
S Stats { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.