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

วิธีการ Overload เมธอดใน C#

การ Overload เมธอด (Method Overloading) ใน C#

Method Overloading คือการสร้างเมธอดหลายเมธอดที่มี ชื่อเดียวกัน แต่ Signature ต่างกัน (พารามิเตอร์ต่างชนิดหรือจำนวน)

2 วิธีหลักในการ Overload

  1. ชนิดข้อมูลพารามิเตอร์ต่างกัน (Different parameter types)
  2. จำนวนพารามิเตอร์ต่างกัน (Different number of parameters)

หมายเหตุ: Return type เพียงอย่างเดียว ไม่สามารถ Overload ได้

ตัวอย่าง: Overload ด้วยชนิดพารามิเตอร์ต่างกัน

void Print(int i)
{
    Console.WriteLine("Printing int: {0}", i);
}

void Print(double f)
{
    Console.WriteLine("Printing float: {0}", f);
}

void Print(string s)
{
    Console.WriteLine("Printing string: {0}", s);
}

ตัวอย่าง: Overload ด้วยจำนวนพารามิเตอร์ต่างกัน

// 2 พารามิเตอร์
public static int MulDisplay(int one, int two)
{
    return one * two;
}

// 3 พารามิเตอร์
public static int MulDisplay(int one, int two, int three)
{
    return one * two * three;
}

// 4 พารามิเตอร์
public static int MulDisplay(int one, int two, int three, int four)
{
    return one * two * three * four;
}

ตัวอย่างการเรียกใช้

Print(5);           // เรียก Print(int)
Print(3.14);        // เรียก Print(double)
Print("Hello");     // เรียก Print(string)

Console.WriteLine(MulDisplay(2, 3));        // 6
Console.WriteLine(MulDisplay(2, 3, 4));     // 24
Console.WriteLine(MulDisplay(2, 3, 4, 5));  // 120

Best Practices

  • ใช้ Overloading เมื่อพฤติกรรมเหมือนกันแตกต่างแค่ Input
  • หลีกเลี่ยง Overloading มากเกินไป (ทำให้สับสน) - ควรใช้ Optional Parameters หรือ Params แทน
  • Document ชัดเจนว่าแต่ละ Overload ทำอะไร