Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การหาดัชนีของสมาชิกสุดท้ายในอาร์เรย์ใน C#

ภาพรวม

เมธอด Array.GetUpperBound(Int32 dimension) คืนดัชนีสูงสุดของมิติที่ระบุ (0-based) สำหรับอาร์เรย์ 1 มิติ คือดัชนีสุดท้าย

ตัวอย่าง 1: อาร์เรย์มีข้อมูล

using System;

public class Demo {
    public static void Main() {
        string[] products = new string[] { "Andy", "Mark", "Gary", "Andre" };

        Console.WriteLine("One or more name begin with 'A'? = {0}",
            Array.Exists(products, ele => ele.StartsWith("A")));
        Console.WriteLine("Is the array having fixed size? = " + products.IsFixedSize);
        Console.WriteLine("Is the array read only? = " + products.IsReadOnly);
        Console.WriteLine("Is the array synchronized? = " + products.IsSynchronized);
        Console.WriteLine("Index of the 1st element = " + products.GetLowerBound(0));
        Console.WriteLine("Index of the last element = " + products.GetUpperBound(0));
    }
}

ผลลัพธ์ตัวอย่าง 1

One or more name begin with 'A'? = True
Is the array having fixed size? = True
Is the array read only? = False
Is the array synchronized? = False
Index of the 1st element = 0
Index of the last element = 3

ตัวอย่าง 2: อาร์เรย์ว่าง

using System;

public class Demo {
    public static void Main() {
        string[] products = new string[] { };

        Console.WriteLine("Is the array having fixed size? = " + products.IsFixedSize);
        Console.WriteLine("Is the array read only? = " + products.IsReadOnly);
        Console.WriteLine("Is the array synchronized? = " + products.IsSynchronized);
        Console.WriteLine("Index of the 1st element = " + products.GetLowerBound(0));
        Console.WriteLine("Index of the last element = " + products.GetUpperBound(0));
    }
}

ผลลัพธ์ตัวอย่าง 2

Is the array having fixed size? = True
Is the array read only? = False
Is the array synchronized? = False
Index of the 1st element = 0
Index of the last element = -1

สรุป

  • GetLowerBound(0) เสมอคืน 0 สำหรับอาร์เรย์ 1 มิติ
  • GetUpperBound(0) คืน Length - 1 (หรือ -1 ถ้าว่าง)
  • ใช้กับอาร์เรย์หลายมิติได้โดยระบุ dimension
  • คุณสมบัติ Length ให้จำนวนสมาชิกทั้งหมด