2017-10-17 52 views
0

我有一些接口和繼承的麻煩。在這裏我的問題:無法實現接口成員,因爲它沒有匹配的返回類型

我有兩個接口:

public interface IElementA 
{ 
    List<IElementA> Child { get; } 
} 

// The goal is to add some properties to the main interface 
public interface IElementB : IElementA 
{ 
    string Name { get; } 
} 

和類實現IElementB

public class ElementB : IElementB 
{ 
    protected List<ElementB> m_Child = new List<ElementB>(); 

    public List<ElementB> Child { get { return m_Child; } } 
    public string Name { get { return "element B"; } 
} 

然後我得到了錯誤:

'ElementB' does not implement interface membre 'IElementA.Child'.

'ELementB.Child' cannot implement 'IElementA.Child' because it does not have the matching return type of 'List<IElementA>'."

我明白,我需要寫

public List<IElementA> Child { get { return m_Child; } } 

並且知道模板技巧,但它只適用於不同類型的IElementA列表。

你有什麼想法來解決我的問題嗎?

問候 JM

+1

'列表'與列表'不是同一種類型,這就是爲什麼你會收到編譯錯誤。 – DavidG

+1

看*協變* – Rahul

+0

DavidG有正確答案 – Picnic8

回答

0

您可以使用泛型:

public interface IElementA<T> 
{ 
    List<T> Child { get; } 
} 

public interface IElementB 
{ 
    string Name { get; } 
} 

public class ElementB : IElementA<ElementB>, IElementB 
{ 
    protected List<ElementB> m_Child = new List<ElementB>(); 

    public List<ElementB> Child { get { return m_Child; } } 
    public string Name 
    { 
     get { return "element B"; } 
    } 

} 

,或者如果你真的看到這裏繼承(我不知道):

public interface IElementB<T> : IElementA<T> where T: IElementA<T> ... 

public class ElementB : IElementB<ElementB> ... 
+0

這可以讓你指定T的任何類型,但它不像OPs代碼那樣受到限制。 (不是我的DV雖然) – DavidG

+0

@DavidG,看編輯,我不太清楚我在這個時間在做什麼。是否有意義? – Sinatr

0

如果您尊重Iterface實施您的清單將看起來如下:

protected List<IElementA> m_Child = new List<IElementA>(); 
    public List<IElementA> Child { get { return m_Child; } } 

所以,你將能夠ElementB元素添加進去:

this.m_Child.Add(new ElementB()); 

如果您只想ElementB在這個列表中,選中插入它之前的類型。

相關問題