【问题标题】:Implement an interface method that gets IEnumerable of interface or of base class as parameter实现一个接口方法,获取接口或基类的 IEnumerable 作为参数
【发布时间】:2021-10-11 04:15:06
【问题描述】:

[以前肯定有人问过类似的问题,但不知怎的,我找不到好的副本,所以打开这个]

一般:

是否可以实现一个接口方法,它将接口或基类的IEnumerable 作为类型参数,其中实现方法IEnumerable 使用实现接口的类的类型参数\派生自基类?

更具体的:

  • 我们有:
    1. 一些接口类型interface IZ 和一些实现类:
      • class CZ1: IZ
      • class CZ2: IZ
    2. 一些基类类型class CZ 和一些派生类:
      • class CZ1: CZ
      • class CZ2: CZ
  • interface IA 定义了一个方法,其参数为:
    • IEnumerable<IZ>,或:
    • IEnumerable<CZ>
  • class CA1 : IA希望用IEnumerable<CZ1>实现接口的方法,而class CA2 :IA希望用IEnumerable<CZ2>实现接口的方法。

这样的实现会引发错误:

没有实现接口成员

  • 有什么方法可以编译这种实现?
  • 使用带有约束的泛型类型参数有什么帮助吗?
  • 如果没有使其直接工作的内置方法,是否有良好的“设计模式”来实现这种“精神”的工作?

完整示例:

用作IEnumerable 类型参数的类型(此处使用IZ,但CZ 的行为方式应相同):

interface IZ {}
class CZ1 : IZ {}
class CZ2 : IZ {}

尝试使用类型参数的类型:

interface IA
{
    void Set(IEnumerable<IZ> records)
}

class CA1 : IA 
{
    public void Set(IEnumerable<CZ1> records) {}  <-- compile error
}

class CA2 : IA
{
    public void Set(IEnumerable<CZ2> records) {}  <-- compile error
}

【问题讨论】:

    标签: c# generics interface ienumerable implementation


    【解决方案1】:

    像这样?

    interface IZ { }
    class CZ1 : IZ { }
    class CZ2 : IZ { }
    
    interface IA<T> where T : IZ
    {
        void Set(IEnumerable<T> records);
    }
    
    class CA1 : IA<CZ1>
    {
        public void Set(IEnumerable<CZ1> records) { }
    }
    class CA2 : IA<CZ2>
    {
        public void Set(IEnumerable<CZ2> records) { }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多