【发布时间】:2009-08-05 18:23:10
【问题描述】:
我想实现一些不同的算法来练习,只是为了看看我到底有多糟糕并变得更好:p
无论如何,我想我会尝试使用IEnumerable<T> 和IOrderedEnumerable<T> 以及其他.Net 集合类型,只是为了兼容(这样我写的东西以后可以更容易地使用)。
但除了使用 OrderBy 和 ThenBy 扩展方法之外,我找不到返回 IOrderedEnumerable<T> 实例的方法。所以我想我必须创建自己的类来实现这个接口。但老实说,界面对我来说不太有意义。可能,但我不确定。
我创建了一个空类,添加了接口,然后让 ReSharper 为我添加了空实现。它看起来像这样:
class MyOrderedEnumerable<T> : IOrderedEnumerable<T>
{
/// <summary>
/// Performs a subsequent ordering on the elements of an <see cref="T:System.Linq.IOrderedEnumerable`1"/> according to a key.
/// </summary>
/// <returns>
/// An <see cref="T:System.Linq.IOrderedEnumerable`1"/> whose elements are sorted according to a key.
/// </returns>
/// <param name="keySelector">The <see cref="T:System.Func`2"/> used to extract the key for each element.</param><param name="comparer">The <see cref="T:System.Collections.Generic.IComparer`1"/> used to compare keys for placement in the returned sequence.</param><param name="descending">true to sort the elements in descending order; false to sort the elements in ascending order.</param><typeparam name="TKey">The type of the key produced by <paramref name="keySelector"/>.</typeparam><filterpriority>2</filterpriority>
public IOrderedEnumerable<T> CreateOrderedEnumerable<TKey>(Func<T, TKey> keySelector, IComparer<TKey> comparer, bool descending)
{
throw new NotImplementedException();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
/// <filterpriority>1</filterpriority>
public IEnumerator<T> GetEnumerator()
{
throw new NotImplementedException();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
/// <filterpriority>2</filterpriority>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
我不明白的是CreateOrderedEnumerable 方法。它究竟是什么意思?好吧,我想它当然会创建一个有序的可枚举,但是如何呢?排序算法本身是否应该进入那里?它会排序什么?该方法没有项目集合,那么在哪里订购集合?你会如何使用这个类?它是否意味着作为一个私有帮助器类来实现,例如需要对东西进行排序的东西?
然后你可能有一个QuickSorter<T> : IOrderedEnumerable<T>,而不是MyOrderedEnumerable<T> : IOrderedEnumerable<T>,它在其构造函数中获取一个集合,并在调用CreateOrderedEnumerable 方法时对其进行排序......但是如果有人调用GetEnumerator,会发生什么情况并在调用该方法之前开始枚举?
哈哈,刚刚发现我前段时间问过类似的问题here。但这只是如果有可能返回一个。所以我想这个问题是对我得到的一个答案的回应=)
【问题讨论】:
标签: c# .net interface ienumerable