类实现与IList的另一个接口属性的接口...如何?

类实现与IList的另一个接口属性的接口...如何?

问题描述:

我有两个接口,像这样:

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;}
}