【问题标题】:Interface with method type depending on implementing class接口与方法类型取决于实现类
【发布时间】:2015-01-29 18:53:00
【问题描述】:

我正在编写一个接口,该接口具有一个应该返回对象列表的方法。列表中的对象将取决于实现类。

例如:

interface IPlayMovie
{
   List<MoviePlayer> RetrievePlayersByMovie();
}

是否可以有一个方法,其中列表的返回类型取决于实现此接口的“MoviePlayer”(或类)?如果有,怎么做?

注意:实现此接口的类不一定是子类,并且没有足够相似的对象结构来归类。

【问题讨论】:

  • 接口不能包含static关键字,public也是。
  • 也许我错了...但是,¿在接口成员中公开?和..¿静态?我错过了什么?
  • 旁注:考虑更准确地编辑帖子的标题......我读到标题是在询问Curiously recurring template pattern,但问题似乎是关于基本的通用界面。

标签: c# oop interface


【解决方案1】:

称为泛型接口,例如:

interface IDataProvider<T>
{
    List<T> Retrieve();
}

class MoviePlayerProvider : IDataProvider<MoviePlayer>
{
    public List<MoviePlayer> Retrieve() { }
}

【讨论】:

  • 我只返回 ICollection&lt;T&gt; 而不是 List&lt;T&gt; 的具体实现
  • 或 IList 如果索引很重要
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-16
  • 1970-01-01
  • 2019-02-10
  • 2016-01-06
  • 2020-06-04
  • 2016-04-17
  • 2011-06-22
相关资源
最近更新 更多