C# Array.IndexOf()方法用于返回一个数组中元素的角标,如果你直接定义一个string[] array = new string[6];数组,它是没有IndexOf方法的,因此我们需要用C#的Array对象来获取某个元素在数组中的角标,使用示例如下:
using System;
class Program
{
static void Main()
{
//
// Example string array is declared.
//
string[] array = new string[6];
array[0] = null;
array[1] = "carrot";
array[2] = "rat";
array[3] = "";
array[4] = "carrot";
array[5] = "apple";
//
// 从第三个元素算起,找出carrot字符串在数组中的角标
int index1 = Array.IndexOf(array, "carrot", 2, 3);
//
//
// Find a nonexistent string.
//
int index2 = Array.IndexOf(array, "banana");
//
// Write the result.
//
Console.WriteLine(index1);
Console.WriteLine(index2);
}
}
Output输出
4
-1C# Arrray对象还有“Array.IndexOf<int>(array, "rat");”与“Array.LastIndexOf(array, "carrot");”分别表示:
返回“rat”所在数组的角标,和IndexOf()方法是一样的
返回最后一个“carrot”字符串所在数组的角标