我在接口和继承方面遇到了一些麻烦。这是我的问题:
我有两个界面:
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'没有实现interface membre'IElementA.Child'。
'ELementB.Child'无法实现'IElementA.Child',因为它没有匹配的返回类型'List&lt; IElementA&gt;'。“
我明白我需要写
public List<IElementA> Child { get { return m_Child; } }
并且知道模板技巧,但它仅适用于不同类型的IElementA的列表。
你有什么想法来解决我的问题吗?
最诚挚的问候 JM
答案 0 :(得分: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> ...
答案 1 :(得分: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
,请在插入之前检查类型。