[英]How to access BinarySearch() method in IList to List initialization without breaking program to interface rule
我有一个代码片段,我无法利用程序接口而不是实现。 在下面的场景中,我无法在“listOne”上执行二进制搜索。 除了IList<int>
还有List<int>
初始化之外还有其他方法吗?
IList<int> listOne = new List<int>();
List<int> listTwo = new List<int>();
// some code goes here.
// Below statement invalid.
//int itemFoundIndex = listOne.BinarySearch(5);
int itemFoundIndex = listTwo.BinarySearch(5);
更新:
在有这种状况的时候的设计的观点,是否需要担心程序接口? 问这个问题嘲笑和单元测试的观点也是如此。
这是.NET集合的一个棘手问题。 层次结构设计得不好。 我认为假设并非每个IList
派生类都能有效地实现BinarySearch
是合理的。 BCL应该包含一个接口ISupportsBinarySearch
和一个使用该接口的扩展方法(如果可用),如果没有,则实现它自己的二进制搜索。
Enumerable.Count
扩展方法就是这样做的。 如果可用,它会委托给ICollection.Count
。
鉴于BCL没有我刚刚提出的这个功能,你需要自己做一些工作。 给自己写一个扩展方法,在任何IList
上进行二进制搜索。 在该方法运行时测试传入的IList
是否实际上是List
。 如果是这种情况委托给List.BinarySearch
方法。
因为Refrence Source可用,所以我查看了Array.BinarySearch
如何工作。 这不是一个复杂的方法所以我编写了自己的扩展方法,首先尝试内置搜索,但如果找不到它,则在IList上进行自己的二进制搜索。
public static class ExtensionMethods
{
[Pure]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int BinarySearch<T>(IList<T> list, T value)
{
if (list == null)
throw new ArgumentNullException("list");
Contract.Ensures((Contract.Result<int>() >= 0) && Contract.Result<int>() <= (list.Count > 0 ? list.Count - 1 : 0) || (Contract.Result<int>() < 0 && ~Contract.Result<int>() <= list.Count));
Contract.EndContractBlock();
return BinarySearch(list, 0, list.Count, value, null);
}
[Pure]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int BinarySearch<T>(IList<T> list, T value, IComparer<T> comparer)
{
if (list == null)
throw new ArgumentNullException("list");
Contract.EndContractBlock();
return BinarySearch(list, 0, list.Count, value, comparer);
}
[Pure]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static int BinarySearch<T>(IList<T> list, int index, int length, T value, IComparer<T> comparer)
{
if (list == null)
throw new ArgumentNullException("list");
Contract.EndContractBlock();
//Try one of the existing implementations of BinarySearch before we do our own.
var asListT = list as List<T>;
if (asListT != null)
return BinarySearch(list, index, length, value, comparer);
var asTypedArray = list as T[];
if (asTypedArray != null)
Array.BinarySearch<T>(asTypedArray, index, length, value, comparer);
var asUntypedArray = list as Array;
if (asUntypedArray != null)
{
if (comparer != null)
{
IComparer nonGenericComparer = comparer as IComparer ?? new ComparerWrapper<T>(comparer);
return Array.BinarySearch(asUntypedArray, index, length, value, nonGenericComparer);
}
else
{
return Array.BinarySearch(asUntypedArray, index, length, value, null);
}
}
if (index < 0 || length < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "length"), "argument is less than 0.");
if (list.Count - index < length)
throw new ArgumentException("index and length do not specify a valid range in the list.");
if (comparer == null)
comparer = Comparer<T>.Default;
int lo = index;
int hi = index + length - 1;
while (lo <= hi)
{
// i might overflow if lo and hi are both large positive numbers.
int i = GetMedian(lo, hi);
int c;
try
{
c = comparer.Compare(list[i], value);
}
catch (Exception e)
{
throw new InvalidOperationException("Comparer failed", e);
}
if (c == 0) return i;
if (c < 0)
{
lo = i + 1;
}
else
{
hi = i - 1;
}
}
return ~lo;
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static int GetMedian(int low, int hi)
{
// Note both may be negative, if we are dealing with arrays w/ negative lower bounds.
Contract.Requires(low <= hi);
Contract.Assert(hi - low >= 0, "Length overflow!");
return low + ((hi - low) >> 1);
}
}
class ComparerWrapper<T> : IComparer
{
private readonly IComparer<T> _comparer;
public ComparerWrapper(IComparer<T> comparer)
{
_comparer = comparer;
}
public int Compare(object x, object y)
{
return _comparer.Compare((T)x, (T)y);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.