繁体   English   中英

实现IEnumerable <T> 在列表中 <T> 派生集合

[英]Implementing IEnumerable<T> in List<T> derived Collection

我收到了一个错误。 这是复制到Console项目并剥离的代码:

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是Covariant。 任何帮助非常感谢。

编辑:代码已经简化

问题是您的属性类型错误。 C#不支持在接口中指定的属性或方法的协变返回类型,也不支持虚方法重写。 您可以使用显式接口实现:

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> ,它是为继承而设计的。)它真的需要这么复杂吗? 如果确实如此,那么为了这个问题,仍然值得减少示例的复杂性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM