我遇到了一个错误。这是复制到控制台项目并精简的代码:
namespace ConsoleApplication1
{
public interface IHexGrid
{
IEnumerable<Hex> hexs { get; } //error related location
}
public class HexC : Hex
{ public int var1;}
public abstract class Hex
{ public int var2; }
public class HexGridC : IHexGrid //error CS0738
{
public List<HexC> hexs { get; set; } // error related location
}
class Program
{
static void Main(string[] args)
{
}
}
}
我收到以下信息:错误 CS0738:
'ConsoleApplication1.HexGridC' does not implement interface
member 'ConsoleApplication1.IHexGrid.hexs'. 'ConsoleApplication1.HexGridC.hexs' cannot
implement 'ConsoleApplication1.IHexGrid.hexs' because it does not have the matching
return type of '`System.Collections.Generic.IEnumerable<ConsoleApplication1.Hex>`'.
不确定为什么 IENumerable 是协变的。非常感谢任何帮助。
编辑:代码已被简化
请您参考如下方法:
问题是您的属性类型错误。 C# 不支持接口(interface)中指定的属性或方法或虚拟方法覆盖的协变返回类型。不过,您可以使用显式接口(interface)实现:
public class HexGridC : IHexGrid //error CS0738: etc
{
public GridElList<HexC> hexs { get; set; } // error related location
IEnumerable<Hex> IHexGrid.hexs { get { return hexs; } }
}
顺便说一句,这一切看起来都非常复杂的代码 - 从 List<T> 派生通常不是一个好主意。首先。 (支持组合,或派生自 Collection<T> ,为继承而设计。)真的需要这么复杂吗?如果是这样,为了问题的缘故,降低示例的复杂性仍然是值得的。
