C# 数组 - GetUpperBound() 方法
C# 数组 GetUpperBound() 方法用于返回一个 32 位整数,表示数组中指定维度最后一个元素的索引。
如果维度为零或大于或等于排名,则此方法抛出 IndexOutOfRangeException。
语法
以下是 C# 数组 GetUpperBound() 方法的语法 -
public int GetUpperBound (int dimension);
参数
此方法接受一个从零开始的数组维度,该维度的上限需要确定 -
返回值
此方法返回数组中指定维度的最后一个元素的索引,如果指定维度为空,则返回 -1。
示例 1:显示最后一个元素的索引
这是 GetUpperBound() 方法的基本示例,用于显示数组中存在的元素数量 -
using System; class Program { static void Main() { int[] Number = new int[] {1, 2, 3, 4, 5}; // 获取长度 int indx = Number.GetUpperBound(0); Console.WriteLine("Index of the last Element " + indx); } }
输出
以下是输出 -
Index of the last Element 4
示例 2:字符串数组最后一个元素的索引
让我们创建一个示例,使用 GetUpperBound() 方法显示字符串数组最后一个元素的索引 -
using System; class Program { static void Main() { string[] Number = new string[] {"Aman", "Gupta", "tutorialspoint", "India"}; // 获取长度 int indx = Number.GetUpperBound(0); Console.WriteLine("Index of the last Element " + indx); } }
输出
以下是输出 -
Index of the last Element 3
示例 3:获取二维数组的最后一个索引
让我们看另一个使用 GetUpperBound() 方法的示例,该示例显示两个维度(维度 0 和维度 1)的最后一个索引 -
using System; class Program { static void Main() { int[,] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; // 获取维度 0 的最后一个索引 int indx_r = matrix.GetUpperBound(0); // 获取维度 1 的最后一个索引 int indx_c = matrix.GetUpperBound(1); Console.WriteLine($"Index - 0D: {indx_r}, Index - 1D: {indx_c}"); } }
输出
以下是输出 -
Index - 0D: 2, Index - 1D: 2
示例 4:获取对象的最后一个索引
让我们看看 GetUpperBound() 方法的另一个版本。在这个版本中,我们显示数组对象的最后一个索引。
using System; class Person { public string Name { get; set; } public int Age { get; set; } } class Program { static void Main() { Person[] people = { new Person { Name = "Aman Kumar", Age = 25 }, new Person { Name = "Rahul Kumar", Age = 26 }, new Person { Name = "Akash Gupta", Age = 26 } }; int indx = people.GetUpperBound(0); Console.WriteLine($"Last index of object: {indx}"); } }
输出
以下是输出 -
Last index of object: 2