[英]unable to implement interface member because it does not have the matching return type
I have some troubles with interface and inheritance. 我在接口和继承方面遇到麻烦。 Here my problem :
这是我的问题:
I have two interfaces : 我有两个界面:
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; }
}
and a class which implement IElementB 和一个实现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"; }
}
Then I got the error: 然后我得到了错误:
'ElementB' does not implement interface membre 'IElementA.Child'.
'ElementB'未实现接口膜'IElementA.Child'。
'ELementB.Child' cannot implement 'IElementA.Child' because it does not have the matching return type of 'List<IElementA>'."
“'ELementB.Child'无法实现'IElementA.Child',因为它没有匹配的返回类型'List <IElementA>'。”
I understand that I need to write 我知道我需要写
public List<IElementA> Child { get { return m_Child; } }
And know the template trick but it's work only with a List of different type of IElementA. 并且知道模板技巧,但是它仅适用于不同类型的IElementA的列表。
Do you have some ideas to solve my problem ? 您有解决我问题的想法吗?
Best Regards JM 此致JM
You can use generics: 您可以使用泛型:
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"; }
}
}
or if you really see inheritance here (I don't): 或者,如果您真的在这里看到继承(我没有):
public interface IElementB<T> : IElementA<T> where T: IElementA<T> ...
public class ElementB : IElementB<ElementB> ...
If you respect the Iterface implementation your list will look to : 如果您尊重Iterface的实现,您的清单将包括:
protected List<IElementA> m_Child = new List<IElementA>();
public List<IElementA> Child { get { return m_Child; } }
So you will be able to add ElementB element into it : 这样您就可以在其中添加ElementB元素:
this.m_Child.Add(new ElementB());
If you want only ElementB
in this list, check the type before insertion on it. 如果仅在此列表中需要
ElementB
,则在插入之前检查类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.