【问题标题】:Is there an interface that specifies that an argument (a collection) can be indexed by an integer?是否有接口指定参数(集合)可以由整数索引?
【发布时间】:2011-10-27 13:20:27
【问题描述】:

我正在尝试使用 OrderedDictionary 作为以下扩展函数的参数(顺便说一下,如果您认为 collection.Reverse().Where(i => predicate(i)).Take(n) 会更好,请告诉我!),但我使用的通用 OrderedDictionary 实现(基于 @987654321 @) 没有实现 IList。

集合只需要通过基于整数的索引提供对其元素的访问(OrderedDictionary 就是这样做的)。

是否有另一种方法来指定此要求,而不会造成重载?

/// <summary>
/// Return n elements, starting from the end of collection, that satisfy predicate.
/// </summary>
/// <param name="collection"></param>
/// <param name="predicate"></param>
/// <param name="n">Max number of elements to return</param>
/// <returns></returns>
public static IEnumerable<T> LastBefore<T>(this IList<T> collection, Func<T, bool> predicate, int n) {
    if (collection == null) 
    {
        throw new ArgumentNullException("collection");
    }
    for (int i = collection.Count - 1; i >= 0; i--) 
    {
        if (n == 0) break;
        if (predicate(collection[i])) 
        {
            --n;
            yield return collection[i];
        }
    }
}

【问题讨论】:

    标签: c# .net list data-structures interface


    【解决方案1】:

    我建议定义一个 IReadableList 接口;如果不是因为读写索引器不能算作只读索引器的实现,那么这样的东西可能是 IList 的父级(恕我直言,无论如何都应该如此)。现有的 IList 实现不会实现 IReadableList,除非包装,唉,但是拥有一个只读列表接口将使协方差的概念更加有用,因为 IReadableList 可以用作 IReadableList

    顺便说一句,我倾向于认为,虽然 IList 不继承自非泛型 IList,但也许它应该继承。如果非泛型实现是只读的,则任何 IList 都可以以类型安全的方式实现 IList。即使从未真正从非泛型 IList 中读取任何对象,实现它也会允许一个需要 IEnumerable 但被赋予 IList 的例程 [它当然实现 IEnumerable,因此隐含IEnumerable] 来获取集合的计数,而不必枚举它。

    【讨论】:

      【解决方案2】:

      根据the MSDN about type constraints,很遗憾没有。

      你最好创建an interface that requires an indexer,但显然你不能用内置类来做到这一点(除非你为此目的定义了一个包装类)。

      【讨论】:

        【解决方案3】:

        您可以在任何IEnumerable&lt;T&gt; 上使用ElementAt。对于实现IList&lt;T&gt; 的集合,这将使用快速索引,而不是枚举所有元素直到请​​求的索引。这提供了只读访问,也适用于没有内置索引支持的集合,尽管会降低性能。您通常会记录该方法以指示支持索引的集合作为传入的参数更可取。

        如果您需要提供读写访问权限,IList&lt;T&gt; 可能是一个合理的约束;如果您需要仅限于索引器的东西,最好的办法是创建一个封装提供的IList&lt;T&gt; 的浅包装类,但只为消费者提供一个索引器。

        【讨论】:

          猜你喜欢
          • 2015-12-27
          • 1970-01-01
          • 2014-05-29
          • 1970-01-01
          • 2011-10-08
          • 2018-09-19
          • 1970-01-01
          • 2019-12-18
          • 1970-01-01
          相关资源
          最近更新 更多