ภาพรวม
พารามิเตอร์ใช้ส่งข้อมูลเข้าและรับข้อมูลกลับจากเมธอด ประกอบไปด้วย:
- Access Specifier - ความมองเห็น (public, private, protected, internal)
- Return type - ชนิดข้อมูลที่คืน (void หากไม่คืนค่า)
- Method name - ชื่อเมธอด (unique, case-sensitive)
- Parameter list - รายการพารามิเตอร์ในวงเล็บ (ชนิด, ลำดับ, จำนวน) เป็นทางเลือก
- Method body - ชุดคำสั่งที่ทำงานจริง
ตัวอย่าง: เมธอด FindMax รับสองจำนวนเต็ม คืนค่าสูงสุด
using System;
public class NumberManipulator
{
public int FindMax(int num1, int num2)
{
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
public static void Main(string[] args)
{
int a = 500;
int b = 750;
int ret;
NumberManipulator n = new NumberManipulator();
ret = n.FindMax(a, b);
Console.WriteLine("Max value = " + ret);
}
}
ผลลัพธ์
Max value = 750
ประเภทพารามิเตอร์เพิ่มเติม
| ประเภท | คำสำคัญ | คำอธิบาย |
|---|---|---|
| Value parameter | (default) | ส่งค่าคัดลอก (pass by value) |
| Reference parameter | ref | ส่งอ้างอิง ต้องกำหนดค่าก่อนเรียก |
| Output parameter | out | ส่งอ้างอิง ต้องกำหนดค่าภายในเมธอด |
| Params parameter | params | รับจำนวนอาร์กิวเมนต์ไม่คงที่ |
| Optional parameter | (default value) | มีค่าเริ่มต้น เรียกได้ไม่ต้องส่ง |
สรุป
- พารามิเตอร์ช่วยให้เมธอดยืดหยุ่น รับข้อมูลนำเข้าและส่งผลลัพธ์กลับ
- เลือกประเภทพารามิเตอร์ให้เหมาะกับความต้องการ (ref/out สำหรับคืนหลายค่า)
- ตั้งชื่อพารามิเตอร์ให้มีความหมาย (camelCase)