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

Parameter Arrays (params) ใน C#

คีย์เวิร์ด params ใน C# ช่วยให้เมธอดรับพารามิเตอร์จำนวนไม่จำกัด (Variable Number of Arguments) ได้ โดยอ้างอิงผ่าน Array ทำให้การเรียกใช้งานยืดหยุ่น ไม่ต้องสร้าง Array ด้วยมือทุกครั้ง

Syntax

returnType MethodName(params type[] parameterName) { }

กฎการใช้งาน params

  • ต้องเป็น **พารามิเตอร์ตัวสุดท้าย** ในลิสต์พารามิเตอร์เท่านั้น
  • สามารถมีได้ **เพียงหนึ่งตัว** ต่อเมธอด
  • Array ที่สร้างขึ้นจะเป็น type[] (Single-dimensional)
  • สามารถส่ง Array ที่สร้างไว้แล้ว หรือส่งค่าแยกต่างหากได้

ตัวอย่างพื้นฐาน

using System;

namespace Program {
    class ParamArray {
        // เมธอดยาวรูปรับจำนวนพารามิเตอร์ได้
        public int AddElements(params int[] arr) {
            int sum = 0;
            foreach (int i in arr) {
                sum += i;
            }
            return sum;
        }
    }

    class Demo {
        static void Main(string[] args) {
            ParamArray app = new ParamArray();
            
            // เรียกใช้ส่งค่าแยกต่างหะ
            int sum = app.AddElements(300, 250, 350, 600, 120);
            Console.WriteLine("The sum is: {0}", sum);  // 1620
            
            // หรือส่ง Array เข้าไปได้เลย
            int[] numbers = { 1, 2, 3, 4, 5 };
            int sum2 = app.AddElements(numbers);
            Console.WriteLine("Sum from array: {0}", sum2);  // 15
            
            // ส่ง 0 argument ได้ (params เป็น optional)
            int sum3 = app.AddElements();
            Console.WriteLine("Empty: {0}", sum3);  // 0
            
            Console.ReadKey();
        }
    }
}

ผลลัพธ์

The sum is: 1620
Sum from array: 15
Empty: 0

ตัวอย่างขั้นสูง

1. ร่วมกับพารามิเตอร์อื่นๆ

public void Log(string level, params string[] messages) {
    Console.WriteLine($"[{level}] {string.Join(" | ", messages)}");
}

// ใช้งาน
Log("INFO", "User login", "IP: 192.168.1.1");
Log("ERROR", "Connection failed");

2. กับ Object Type (รับอะไรก็ได้)

public void PrintAll(params object[] items) {
    foreach (var item in items) {
        Console.WriteLine(item?.ToString() ?? "null");
    }
}

PrintAll(1, "Hello", 3.14, true, new DateTime(2024,1,1));

3. Method Overloading กับ params

public void Process(int x) { Console.WriteLine("Single: " + x); }
public void Process(params int[] xs) { Console.WriteLine("Multiple: " + string.Join(",", xs)); }

// Process(5)       -> เรียก overload แรก (Better match)
// Process(1,2,3)   -> เรียก overload params

Params Collections (C# 13+ / .NET 9+)

รองรับ Collection Types อื่นๆ ไม่ใช่แค่ Array:

// ต้องการ .NET 9+ และ C# 13+
public void Process(params List numbers) { }
public void Process(params IEnumerable numbers) { }
public void Process(params ReadOnlySpan numbers) { }

Performance Considerations

สถานการณ์ ผลกระทบ
เรียกบ่อยมาก (Hot Path) สร้าง Array ใหม่ทุกครั้ง → GC Pressure
จำนวน Argument น้อย Overhead น้อย ไม่เป็นปัญหา
ใช้ params ReadOnlySpan<T> Zero-allocation (Stack allocated) - Best Performance

Best Practices

  • ใช้ params เมื่อจำนวน Argument ไม่แน่นอนแต่โดยปกติไม่มาก
  • หลีกเลี่ยงใน Hot Paths ที่ Critical Performance - ใช้ Overloads แทน
  • พิจารณา IEnumerable<T> หรือ ReadOnlySpan<T> แทนถ้าไม่ต้องการ Array
  • Document ชัดเจนว่า Parameter คืออะไร (XML Comments)