无法实现接口成员,因为它没有匹配的返回类型List <IInterface>

Ser*_*pov 23 c# generics inheritance interface

我有接口IChildIParent.IParent有一个成员List<IChild>.

我希望有类实现IParent每个类都有一个实现的成员的位置IChild:

public interface IChild
{ 
}  

public interface IParent
{  
    List<IChild> a { get; set; }
} 

public class ChildA : IChild
{ 
} 

public class ChildB : IChild
{ 
} 

public class ParentA : IParent
{ 
    public List<ChildA> a { get; set; }
}

public class ParentB : IParent
{ 
    public List<ChildB> a { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

但是,这段代码不会编译.错误是:

`MyApp.Data.ParentA` does not implement interface member `MyApp.Data.IParent.a`.
`MyApp.Data.ParentA.a` cannot implement `MyApp.Data.IParent.a` because it does not have
the matching return type of `System.Collections.Generic.List<MyApp.Data.IChild>`.
Run Code Online (Sandbox Code Playgroud)

Vol*_*lma 37

使IParent通用:

public interface IChild
{
}

public interface IParent<TChild> where TChild : IChild
{
    List<TChild> a { get; set; } 
}

public class ChildA : IChild {  }   

public class ChildB : IChild {  }   

public class ParentA : IParent<ChildA>
{
    public List<ChildA> a { get; set; }
}

public class ParentB : IParent<ChildB>
{
    public List<ChildB> a { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

  • 您能详细说明解决方案背后的基本原理吗? (7认同)