Skip to main content
 首页 » 编程设计

c#之如何实现定义另一个接口(interface)元素的接口(interface)

2024年02月23日17傻小

Interface A 
    { 
      string x {get;set;} 
      IEnumarable<InterfaceB> DetailList { get; set; } 
    } 
    Interface B 
    { 
     int z; 
     int y; 
    } 
 
    Class B :Interface B 
    { 
      implements z; 
      implements y; 
    } 
    Class A :Interface A 
    { 
      implements x; 
      IEnumarable<ClassB> DetailList {get;set;} // This line is giving trouble. 
    } 

此代码是否违反了 OO 概念。我想如果我从 InterfaceB 派生 ClassB,那么我可以在我的 ClassA 中使用 ClassB 而不是 InterfaceB。 VS 不喜欢这样,它要求我在 ClassA 中使用 InterfaceB 而不是 ClassB。 有没有其他方法可以做到这一点。

我愿意考虑其他设计选项,我有一些域对象,其属性由接口(interface) A 定义,每个域对象都有对应的对象,由接口(interface) B 定义 例如 音乐会(A) 音乐会地点(B) 喜剧表演(A) 喜剧表演地点(B)

如果您认为我不够清楚,请随时提出更多问题。
提前致谢

请您参考如下方法:

你可以这样做:

public interface InterfaceA<T> where T : InterfaceB 
{ 
    string x {get;set;} 
    IEnumerable<T> DetailList { get; set; } 
} 
 
public interface InterfaceB 
{ 
    int z { get; } 
    int y { get; } 
} 
 
public class ClassB : InterfaceB 
{ 
    public int z { get; private set; } 
    public int y { get; private set; } 
} 
 
public class ClassA : InterfaceA<ClassB> 
{ 
    public int z { get; private set; } 
 
    public string x { get; set; } 
 
    public IEnumerable<ClassB> DetailList {get;set;}  
} 

但我不确定这是否适合您?

查看此处了解更多信息:c# interface implemention - why does this not build?