2011-10-04 54 views
1

我收到一個錯誤。這裏是整個複製到一個控制檯項目和精簡代碼:實施IEnumerable <T>列表<T>衍生集合

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是協變。任何幫助非常感謝。

編輯:代碼已被簡化

+2

老實說,編譯錯誤信息不能比這更好...它告訴你到底該怎麼做':)' – Kobi

回答

4

問題是您的屬性是錯誤的類型。 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>派生,即爲繼承設計)。它真的需要如此複雜嗎?如果確實如此,爲了解決這個問題,還是值得降低這個例子的複雜性。

+0

我相信它確實需要那麼複雜,但是對於不進一步簡化問題表示歉意開始。我忘記了界面屬性限制。我想你可以使用不同的屬性名稱,只需在get中顯式返回,但使用顯式接口實現真的很乾淨!謝謝。 –

相關問題