当Array.BinarySearch表示具有负索引的数组时,它意味着什么?

时间:2014-06-24 16:59:49

标签: c# .net arrays

.NET中的

The documentation for Array.BinarySearch表示它不适用于具有负索引的数组。据我所知,.NET只有具有正索引的数组,并且不允许从System.Array类型继承。

为什么文档说明了这一点以及它是如何实现的?

  

此方法不支持搜索包含负索引的数组。必须在调用此方法之前对数组进行排序。

2 个答案:

答案 0 :(得分:5)

您可以创建一个数组,让您为数组提供负索引:

var grid = (int[,])Array.CreateInstance(typeof(int),new[] {7,7}, new[] {-3,-3});
for (int r = -3 ; r <= 3 ; r++) {
    for (int c = -3 ; c <= 3 ; c++) {
        grid[r,c] = 10+r + c;
    }   
}

Demo on ideone.

您也可以使用单个维创建一个数组,但由于CLR对一维数组使用特殊类型,因此无法将其转换为int[]。但是,您可以通过Array API将此类数组与负索引一起使用。文档说不允许您将此类数组传递给BinarySearch方法。

答案 1 :(得分:2)

有一种方法可以在.NET中创建带负索引的Array,使用Array.CreateInstance工厂方法的重载,您可以在其中指定索引的下限:

public static Array CreateInstance(
    Type elementType,
    int[] lengths,
    int[] lowerBounds
)

长度为10且索引从-10开始的1维数组:

var a = Array.CreateInstance(typeof(string), new[] { 10 }, new[] { -10 });
a.SetValue("test", -5);
Console.WriteLine(a.GetValue(-5));
Console.WriteLine(a.GetLowerBound(0));

// yields:
// test
// -10

另请注意,具有负索引下限的1维数组无法强制转换为向量,例如int[],它必须基于0进行索引。这种数组与矢量或基于0的索引数组的类型不同:

Console.WriteLine((Array.CreateInstance(typeof(int), new[] { 1 }, new[] { -1 })).GetType());
Console.WriteLine((Array.CreateInstance(typeof(int), new[] { 1 }, new[] { 0 })).GetType());
Console.WriteLine((new int[] {}).GetType());

// yields:
// System.Int32[*]
// System.Int32[]
// System.Int32[]

(int[])Array.CreateInstance(typeof(int), new[] { 1 }, new[] { -1 })

// throws:
// System.InvalidCastException