C#中的Array.LastIndexOf()方法用于搜索指定的对象,并返回整个Array中最后一次出现的索引。
以下是语法-
public static int LastIndexOf<T> (T[] array, T val);
上面的参数arr是要搜索的一维,从零开始的数组,而Val是要在数组中定位的对象。
现在让我们看一个实现Array.LastIndexOf()方法的示例-
using System; public class Demo{ public static void Main(){ Console.WriteLine("Array elements..."); string[] arr = { "car", "bike", "truck", "bus"}; for (int i = 0; i < arr.Length; i++){ Console.Write("{0} ", arr[i]); } Console.WriteLine(); int lastIndex = Array.LastIndexOf(arr, "bus"); Console.WriteLine("Last Ocurrence of element bus is at index = "+lastIndex); } }
输出结果
这将产生以下输出-
Array elements... car bike truck bus Last Ocurrence of element bus is at index = 3