我刚刚更改了数组中元素的索引。当我运行代码并使用Array.BinarySearch()搜索特定元素时;它仍然返回与我更改它们之前相同的索引。
static void Main(string[] args)
{
int indexno;
string schooltype;
Array schools= Array.CreateInstance(typeof(string), 3);
schools.SetValue("Middle School", 0);
schools.SetValue("High School", 1);
schools.SetValue("Univercity", 2);
Array.Sort(schools);
Console.Write("What type of school are you looking for: ");
schooltype = Console.ReadLine();
indexno = Array.BinarySearch(schools, schooltype.ToString());
if (indexno<0)
{
Console.WriteLine("School type not exist. ");
}
else
{
Console.WriteLine("Index of the school type is " + indexno);
}
我从来没有在实际的生产代码中看到一个变量声明为Array
。我们可以使用Array
静态方法,但是这样声明变量是不可能的。
static void Main(string[] args)
{
string[] schools = {"Middle School", "High School", "University"};
Array.Sort(schools); //uses default comparer... be careful of mixed case values
//verify new order
Console.WriteLine(String.Join("n", schools));
Console.Write("What type of school are you looking for: ");
var schooltype = Console.ReadLine();
var result = "School type not exist. ";
var index = Array.BinarySearch(schools, schooltype);
if (index >= 0)
{
result = $"Index of the school type is {index}";
}
Console.WriteLine(result);
}
这段代码返回了所有三种可能的学校类型的正确索引:
https://dotnetfiddle.net/fjpOOb