类实现与IList的另一个接口属性的接口...如何? [英] Class that implements an interface with IList of another interface property...how to?
问题描述
我有两个接口,像这样:
I have two interfaces like these:
public interface IMyInterface1
{
string prop1 { get; set; }
string prop2 { get; set; }
}
public interface IMyInterface2
{
string prop1 { get; set; }
IList<IMyInterface1> prop2 { get; set; }
}
我已经定义了两个实现接口的类:
I have defined two classes that implement the interfaces:
public class MyClass1 : IMyInterface1
{
public string prop1 {get; set;}
public string prop2 {get; set;}
}
public class MyClass2 : IMyInterface2
{
public string prop1 {get; set;}
public IList<MyClass1> prop2 {get; set;}
}
但是当我构建代码时,我有以下错误信息:
but when I build the code I have the following error message:
'ClassLibrary1.MyClass2'不实现接口成员ClassLibrary1.IMyInterface2.prop2。 'ClassLibrary1.MyClass2.prop2'不能实现'ClassLibrary1.IMyInterface2.prop2',因为它没有匹配的返回类型'System.Collections.Generic.IList'
'ClassLibrary1.MyClass2' does not implement interface member 'ClassLibrary1.IMyInterface2.prop2'. 'ClassLibrary1.MyClass2.prop2' cannot implement 'ClassLibrary1.IMyInterface2.prop2' because it does not have the matching return type of 'System.Collections.Generic.IList'
如何在我的类上实现IMyInterface2的IList prop2?
How can I do to implement the "IList prop2" of IMyInterface2 on my class?
推荐答案
属性类型 IList< IMyInterface1>
,而不是 IList< class实现IMyInterface1>
。
如果您希望这样工作,您需要使 IMyInterface2
通用:
You'll need to make IMyInterface2
generic if you want this to work:
public interface IMyInterface2<T> where T : IMyInterface1
{
string prop1 { get; set; }
IList<T> prop2 { get; set; }
}
然后 MyClass2
成为:
public class MyClass2 : IMyInterface2<MyClass1>
{
public string prop1 {get; set;}
public IList<MyClass1> prop2 {get; set;}
}
这篇关于类实现与IList的另一个接口属性的接口...如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!