Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Sử dụng GetUpperBound() của lớp Array trong C#


Phương thức Array.GetUpperBound() lấy chỉ số lớn nhất (upper bound) của chiều chỉ định trong mảng.

Ví dụ

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Array arr = Array.CreateInstance(typeof(String), 6);
            arr.SetValue("One", 0);
            arr.SetValue("Two", 1);
            arr.SetValue("Three", 3);
            arr.SetValue("Four", 4);
            arr.SetValue("Five", 5);
            
            // Chỉ số lớn nhất của chiều 0
            Console.WriteLine("Upper Bound (chiều 0): {0}", arr.GetUpperBound(0));
            
            // Với mảng 2 chiều
            int[,] matrix = new int[3, 4];
            Console.WriteLine("Upper Bound hàng: {0}", matrix.GetUpperBound(0)); // 2
            Console.WriteLine("Upper Bound cột: {0}", matrix.GetUpperBound(1));  // 3
            
            Console.ReadLine();
        }
    }
}

Kết quả

Upper Bound (chiều 0): 5
Upper Bound hàng: 2
Upper Bound cột: 3

Giải thích

  • Mảng 1 chiều kích thước 6: chỉ số 0..5 → UpperBound = 5
  • Mảng 2 chiều 3x4: hàng 0..2 (UpperBound=2), cột 0..3 (UpperBound=3)
  • GetUpperBound(dimension) = GetLength(dimension) - 1

Ứng dụng

// Duyệt mảng an toàn không cần biết kích thước trước
for (int i = 0; i <= arr.GetUpperBound(0); i++)
{
    for (int j = 0; j <= arr.GetUpperBound(1); j++)
        Console.Write(arr[i, j] + " ");
    Console.WriteLine();
}