2017-10-17 51 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在这个列表中,选中插入它之前的类型。

相关问题