我正在尝试将旧项目从使用 ArrayList 集合升级到 List。一切都很顺利,除了转换 ArrayList.BinarySearch。虽然 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);
}
}