我正在尝试将一个旧项目从使用ArrayList集合升级到使用List集合。除了将ArrayList.BinarySearch转换为List之外,一切都很顺利。虽然List有一个相应的方法,但是ArrayList.BinarySearch有一个重载,它接受一个任意对象,而List.BinarySearch则要求T类型的对象。以下是示例。
我如何有效地用List替换这个ArrayList功能?或者我必须自己写一个新函数吗?
class Pod {
public DateTime Start { get; set; }
}
class TimeRange: IComparer {
TimeSpan StartsAt { get; set; }
ITimeRangeComparer TimeComparer { get; set; }
public int Compare(object x, object y) {
// there is more to it, but basically compares time ranges
return comparer.Compare((TimeRange) x, (TimeRange) y);
}
}
class Manager {
void DoStuff() {
ArrayList alPods = GetPodsAL();
List<Pod> lstPods = GetPodsLST();
int stopIndex;
TimeRange startPoint = GetStartPoint();
TimeRange stopPoint = GetStopPoint();
// ArrayList works fine
stopIndex = alPods.BinarySearch(stopPoint, startPoint.TimeComparer);
// Fails because the method demands that `stopPoint` be of type Pod
stopIndex = lstPods.BinarySearch(stopPoint, startPoint.TimeComparer);
}
}
List<T>
,为什么要传入一个不是类型T
的对象呢?这样的对象可能不在列表中。 - Adam RobinsonFunc<T, int>
的 BinarySearch 版本。这是最通用的二分查找版本,但框架不提供它 :( - usr