3

I am trying to upgrade an old project from using ArrayList collections to List. Everything went pretty smooth, except for converting ArrayList.BinarySearch. While List has a corresponding method, the ArrayList.BinarySearch has an overload that accepts an arbitrary object while List.BinarySearch demands an object of type T. Example below.

How can I effectively replace this ArrayList functionality with List? Or do I have to roll my own?

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);
   }
}
4

1 に答える 1

1

を使用するのと同じメソッドを使用するには、 を配列ArrayList.BinarySearchに変換してを呼び出します。残念ながら、新しい配列への変換/コピーを行う必要があります。List<T>Array.BinarySearch(Array, object)

List<SomeType> list;
SomeType value;
// ...
Array.BinarySearch(list.ToArray(), value)

ただし、 aList<T>は強く型付けされているため、 type のみが含まれますT。なんらかの理由でその型がリストにあるかどうかわからない場合は、事前に確認するか、それを行う拡張メソッドを作成してください。

public static class ListExtensionMethods
{
    public static int BinarySearch<T>(this List<T> list, object value)
    {
        if (value is T)
            return list.BinarySearch((T)value);
        return -1;
    }
}
于 2013-03-09T08:18:49.253 に答える