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

ส่ง Parameter ให้ Method ใน C#

การส่ง Parameter ให้ Method ใน C#

C# รองรับ 4 รูปแบบการส่งพารามิเตอร์

1. Pass by Value (Default)

  • Copy ค่าของ Variable ไปให้ Parameter
  • การเปลี่ยนแปลงใน Method ไม่ส่งผล ต่อตัวแปรต้นทาง
  • Value Types: Copy ค่า, Reference Types: Copy Reference (แต่อ็อบเจกต์เดียวกัน)

ตัวอย่าง


using System;

namespace Demo
{
    class NumberManipulator
    {
        public void Swap(int x, int y) // Pass by Value
        {
            int temp = x; x = y; y = temp;
            Console.WriteLine($"Inside Swap: x={x}, y={y}");
        }
    }
    
    class Program
    {
        static void Main()
        {
            NumberManipulator n = new NumberManipulator();
            int a = 50, b = 150;
            
            Console.WriteLine($"Before: a={a}, b={b}"); // 50, 150
            n.Swap(a, b);
            Console.WriteLine($"After: a={a}, b={b}");  // 50, 150 (ไม่เปลี่ยน!)
            Console.ReadLine();
        }
    }
}

2. Pass by Reference (ref)

  • ส่ง Reference ของ Variable (Address)
  • การเปลี่ยนแปลงใน Method ส่งผล ต่อตัวแปรต้นทาง
  • Variable ต้อง Initialized ก่อนส่ง

void Swap(ref int x, ref int y) { int t=x; x=y; y=t; }
// เรียก: Swap(ref a, ref b); // a,b เปลี่ยนค่าจริง

3. Output Parameter (out)

  • คล้าย ref แต่ Variable ไม่ต้อง Initialized ก่อน
  • Method บังคับ ต้อง Assign ค่าให้ Parameter ก่อน Return
  • ใช้สำหรับ Return หลายค่า

bool TryParse(string s, out int result)
{
    result = 0; // ต้อง Assign
    return int.TryParse(s, out result);
}
// เรียก: if (TryParse("123", out int n)) ...

4. In Parameter (in - C# 7.2+)

  • Pass by Reference แบบ Read-only
  • Method ไม่สามารถแก้ไข Parameter ได้ (Compile-time Error)
  • เหมาะสำหรับ Struct ใหญ่ๆ ป้องกัน Copy

void ReadOnly(in BigStruct data) 
{
    // data = new BigStruct(); // Error!
    Console.WriteLine(data.Value);
}

5. Params Array (params)

  • รับจำนวน Argument แปรได้ (0 หรือมากกว่า)
  • ต้องเป็น Parameter ตัวสุดท้าย

int Sum(params int[] numbers) => numbers.Sum();
// เรียก: Sum(1,2,3), Sum(new[]{1,2,3}), Sum()

สรุปตารางเปรียบเทียบ

KeywordDirectionInit RequiredCan ModifyUse Case
(none)InYesLocal Copy OnlyDefault, Simple Values
refIn/OutYesYesSwap, Modify Caller's Var
outOutNoYes (Must Assign)Multiple Return, TryParse
inInYesNo (Compile Error)Large Struct Read-only
paramsIn (Array)N/AArray ElementsVariable Arguments