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

Generic Methods ใน C#

Generic Methods (เมธอดเจเนอริก) ใน C#

Generic Method ช่วยให้เขียนเมธอดเดียวทำงานกับหลายชนิดข้อมูลได้ โดยระบุ Type Parameter <T> ก่อนชื่อเมธอด

ไวยากรณ์

<Access Modifier> <Return Type> <Method Name><T>(Parameter List)
{
    // Method Body
}

ตัวอย่าง: Swap แบบ Generic

using System;
using System.Collections.Generic;

namespace Demo
{
    class Program
    {
        // Generic Method
        static void Swap<T>(ref T lhs, ref T rhs)
        {
            T temp = lhs;
            lhs = rhs;
            rhs = temp;
        }

        static void Main(string[] args)
        {
            int a = 45, b = 60;
            char c = 'K', d = 'P';

            Console.WriteLine($"Int before: a={a}, b={b}");
            Console.WriteLine($"Char before: c={c}, d={d}");

            Swap(ref a, ref b);
            Swap(ref c, ref d);

            Console.WriteLine($"Int after: a={a}, b={b}");
            Console.WriteLine($"Char after: c={c}, d={d}");
            Console.ReadKey();
        }
    }
}

ผลลัพธ์

Int before: a=45, b=60
Char before: c=K, d=P
Int after: a=60, b=45
Char after: c=P, d=K

ข้อดีของ Generic Methods

  • Type Safety: Compiler ตรวจสอบชนิดข้อมูลที่ Compile-time
  • Code Reuse: เขียนครั้งเดียว ใช้กับหลาย Type ได้
  • Performance: หลีกเลี่ยง Boxing/Unboxing สำหรับ Value Types
  • Constraints: สามารถจำกัด Type Parameter ได้ (where T : IComparable, class, struct, new())

ตัวอย่าง Constraints

// T ต้องมี Constructor ไม่มีพารามิเตอร์
public T CreateInstance<T>() where T : new()
{
    return new T();
}

// T ต้อง Implement IComparable
public int Compare<T>(T a, T b) where T : IComparable<T>
{
    return a.CompareTo(b);
}