📜  C#| Array.LastIndexOf<T> (T [],T)方法

📅  最后修改于: 2021-05-29 14:41:48             🧑  作者: Mango

Array.LastIndexOf (T [],T)方法用于搜索指定的对象。它返回整个数组中最后一次出现的索引。

句法:

public static int LastIndexOf(T[] array, T value);

参数:

返回值:返回整个数组中最后一次出现的值的System.Int32类型的从零开始的索引,如果找到则返回-1。

异常如果数组为null,则此方法将提供ArgumentNullException

下面的示例说明了上面讨论的方法的使用:

范例1:

// C# program to demonstrate
// Array.LastIndexOf(T[], value)
// Method
using System;
  
class Geeks {
  
    // Main Method
    public static void Main()
    {
  
        // Creates and initializes a new 
        // Array with three elements of the
        // same value.
        string[] str = {"C", "C++", "C#", "Java", 
                          "Python", "C#", "C++", 
                                     "C#", "CSS"};
          
        // printing the Elements of an Array
        Console.WriteLine("Elements of Array: ");
        Console.WriteLine();
        foreach(string str1 in str)
        {
            Console.WriteLine(str1);
        }
          
          
        Console.Write("\nLast Occurrence of C#: ");
          
        // printing the last index of C# 
        // using Array.LastIndexOf(T[],
        // value) Method
        Console.Write(Array.LastIndexOf(str, "C#"));
          
          
        Console.Write("\nLast Occurrence of C++: ");
          
        // printing the last index of C++ 
        // using Array.LastIndexOf(T[],
        // value) Method
        Console.Write(Array.LastIndexOf(str, "C++"));
    }
}

输出:

Elements of Array: 

C
C++
C#
Java
Python
C#
C++
C#
CSS

Last Occurrence of C#: 7
Last Occurrence of C++: 6

范例2:

// C# program to demonstrate
// Array.LastIndexOf(T[], value)
// Method
using System;
  
class Geeks {
  
    // Main Method
    public static void Main()
    {
  
        // creating and intializing an array
        int[] arr = {1, 2, 3, 4, 1, 2,
                       3, 4, 2, 4, 2};
          
        // printing the Elements of an Array
        Console.WriteLine("Elements of Array: ");
        Console.WriteLine();
        foreach(int i in arr)
        {
            Console.WriteLine(i);
        }
          
        // using Array.LastIndexOf(T[],
        // value) Method
        // it will give runtime error as 
        // array parameter is null
        Console.Write(Array.LastIndexOf(null, 1));
          
      
    }
}

运行时错误:

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.array.lastindexof?view=netframework-4.7.2#System_Array_LastIndexOf__1___0_____0_