简体   繁体   English

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

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

I'm getting an error. 我收到了一个错误。 Here's the code copied across to a Console project and stripped down: 这是复制到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)
    {
    }
}
}

I'm getting the following: error CS0738: 我得到以下内容:错误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>`'.

Not sure why as IENumerable is Covariant. 不知道为什么IENumerable是Covariant。 Any help much appreciated. 任何帮助非常感谢。

Edit: the code has been simplified 编辑:代码已经简化

The problem is that your property is of the wrong type. 问题是您的属性类型错误。 C# doesn't support covariant return types for properties or methods specified in interfaces or for virtual method overriding. C#不支持在接口中指定的属性或方法的协变返回类型,也不支持虚方法重写。 You can use explicit interface implementation though: 您可以使用显式接口实现:

public class HexGridC : IHexGrid //error CS0738: etc
{        
    public GridElList<HexC> hexs { get; set; } // error related location

    IEnumerable<Hex> IHexGrid.hexs { get { return hexs; } }
}

As an aside, this all seems terribly complicated code - and it's generally not a good idea to derive from List<T> in the first place. 顺便说一下,这一切似乎都非常复杂 - 而且从一开始就从List<T>派生出来通常不是一个好主意。 (Favour composition, or derive from Collection<T> which is designed for inheritance.) Does it really need to be so complicated? (赞成组合,或派生自Collection<T> ,它是为继承而设计的。)它真的需要这么复杂吗? If it does, it would still have been worth cutting down the complexity of the example for the sake of the question. 如果确实如此,那么为了这个问题,仍然值得减少示例的复杂性。

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

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