【发布时间】:2015-08-28 21:56:33
【问题描述】:
我有一堂课:
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.Structure.Stats”无法实现“Server.Models.Structures.IStructure.Stats”,因为它没有“Server.Models.Structures.StructureStats”的匹配返回类型。 C:\SRDevGit\freecon-galactic-server\SRServer\Server.Models\Structures\Structure.cs
我不确定问题是什么; Structure.Stats {get;} 的返回类型应保证与接口定义匹配,因为泛型类型 S 被定义为从 StructureStats 派生的
where S:StructureStats, new()
我错过了什么?如果可能的话,我想避免使 IStructure 通用化,因为它会使
的集合复杂化<IStructure<GenericType>>
因为 GenericType 是一个多态类。
【问题讨论】:
-
C# 不支持返回类型差异。
-
你真正想要达到什么目的?这种方法似乎充其量是令人费解的。
-
我试图避免强制转换。 Structure、StructureModel 和 StructureStats 都是多态类,但是它们受到约束,因此特定的派生结构必须与特定的派生 StructureModel 和特定的派生 StructureStats 一起使用。主要困难在于选择将对象数据分离到自己的类(StructureModel)中,类似于 MVVM 模式。