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

Array Class ใน C# - Base Class ของ Arrays ทั้งหมด

Array Class (System.Array) เป็น **Base Class แบบ Abstract** ของ Arrays ทุกประเภทใน C# ไม่ว่าจะเป็น 1D, 2D, Jagged หรือ Generic Arrays ทุกตัวสืบทอดมาจากคลาสนี้ จัดอยู่ใน Namespace System

Properties ของ Array Class

Property คำอธิบาย
IsFixedSize คืนค่า true เสมอ (Arrays มีขนาดคงที่)
IsReadOnly คืนค่า false เสมอ (Arrays อ่าน-เขียนได้)
Length จำนวน Elements ทั้งหมด (32-bit Integer)
LongLength จำนวน Elements ทั้งหมด (64-bit Integer) - สำหรับ Array ใหญ่ > 2^31
Rank จำนวน Dimensions (Rank) ของ Array

ตัวอย่าง: ใช้ Properties ต่างๆ

using System;

class Program {
    static void Main() {
        // 1D Array
        int[] arr1D = new int[10];
        Console.WriteLine($"1D: Length={arr1D.Length}, Rank={arr1D.Rank}");
        
        // 2D Array
        int[,] arr2D = new int[3, 4];  // 3 rows, 4 cols = 12 elements
        Console.WriteLine($"2D: Length={arr2D.Length}, Rank={arr2D.Rank}");
        Console.WriteLine($"  GetLength(0)={arr2D.GetLength(0)} (Rows)");
        Console.WriteLine($"  GetLength(1)={arr2D.GetLength(1)} (Cols)");
        
        // 3D Array
        int[,,] arr3D = new int[2, 3, 4];  // 24 elements
        Console.WriteLine($"3D: Length={arr3D.Length}, Rank={arr3D.Rank}");
        Console.WriteLine($"  LongLength={arr3D.LongLength}");
        
        // Jagged Array (Array of Arrays) - Rank = 1
        int[][] jagged = new int[3][];
        jagged[0] = new int[2];
        jagged[1] = new int[3];
        jagged[2] = new int[4];
        Console.WriteLine($"Jagged: Length={jagged.Length}, Rank={jagged.Rank}");
        // Length = 3 (จำนวน Sub-arrays), Rank = 1
    }
}

ผลลัพธ์

1D: Length=10, Rank=1
2D: Length=12, Rank=2
  GetLength(0)=3 (Rows)
  GetLength(1)=4 (Cols)
3D: Length=24, Rank=3
  LongLength=24
Jagged: Length=3, Rank=1

Static Methods สำคัญของ Array Class

Method คำอธิบาย
CreateInstance สร้าง Array แบบ Dynamic (Type รู้ตอน Runtime)
Copy Copy Elements ระหว่าง Arrays (เร็วกว่า Loop)
CopyTo Copy ทั้ง Array ไป Array อื่น
Sort เรียงลำดับ (In-place)
Reverse กลับลำดับ (In-place)
BinarySearch ค้นหาแบบทวิภาค (ต้อง Sorted)
IndexOf / LastIndexOf หา Index ของค่า
Find / FindAll / FindIndex ค้นหาด้วย Predicate
Resize เปลี่ยนขนาด Array (สร้างใหม่ Copy)
Clear Set Elements เป็น Default Value (0, null, false)
ConvertAll Convert ทุก Element ด้วย Converter
ForEach Action ทุก Element
AsReadOnly Wrap เป็น ReadOnlyCollection

ตัวอย่าง: CreateInstance (Dynamic Array Creation)

using System;

class Program {
    static void Main() {
        // สร้าง Array โดย Type รู้ตอน Runtime
        Type elementType = typeof(string);
        int length = 3;
        
        Array arr = Array.CreateInstance(elementType, length);
        
        // Set Values
        arr.SetValue("Electronics", 0);
        arr.SetValue("Clothing", 1);
        arr.SetValue("Appliances", 2);
        
        Console.WriteLine("Length: " + arr.Length);  // 3
        Console.WriteLine("Rank: " + arr.Rank);      // 1
        
        // Get Values
        for (int i = 0; i < arr.Length; i++) {
            Console.WriteLine($"[{i}] = {arr.GetValue(i)}");
        }
    }
}

ผลลัพธ์

Length: 3
Rank: 1
[0] = Electronics
[1] = Clothing
[2] = Appliances

ตัวอย่าง: Copy และ Resize

int[] source = { 1, 2, 3, 4, 5 };
int[] dest = new int[10];

// Copy 3 elements from source[0] to dest[2]
Array.Copy(source, 0, dest, 2, 3);
// dest = {0, 0, 1, 2, 3, 0, 0, 0, 0, 0}

// Resize - ขยาย/หด Array
Array.Resize(ref source, 8);  // source ตอนนี้มี 8 Elements (3 ตัวใหม่เป็น 0)
Array.Resize(ref source, 3);  // ตัดเหลือ 3 Elements

Array Covariance (Array Covariance)

string[] strings = { "A", "B", "C" };
object[] objects = strings;  // Implicit Conversion (Covariance)

// ⚠️ Runtime Check - Type Safety
objects[0] = "Hello";  // OK - string is object
// objects[0] = 123;    // Runtime Error: ArrayTypeMismatchException

// Note: List ไม่สามารถ Assign ให้ List ได้ (Invariant)

Best Practices

  • ใช้ Length แทน Count() (LINQ) สำหรับ Array - O(1) Property
  • ใช้ Array.Copy หรือ Buffer.BlockCopy แทน Loop สำหรับ Copy จำนวนมาก
  • พิจารณา Span<T> / Memory<T> สำหรับ Slicing โดยไม่ Copy
  • หลีกเลี่ยง Array.Resize ใน Hot Path - ใช้ List<T> แทน
  • ใช้ ArrayPool<T> สำหรับ Array Reuse (Reduce GC Pressure)