Generics อนุญาตให้คุณเขียนคลาสหรือเมธอดที่สามารถทำงานกับข้อมูลประเภทใดก็ได้ ประกาศวิธีการทั่วไปด้วยพารามิเตอร์ประเภท -
static void Swap(ref T lhs, ref T rhs) {} ในการเรียกวิธีการทั่วไปที่แสดงด้านบนนี้ เป็นตัวอย่าง –
Swap(ref a, ref b);
ให้เราดูวิธีการสร้างวิธีการทั่วไปใน C# -
ตัวอย่าง
using System;
using System.Collections.Generic;
namespace Demo {
class Program {
static void Swap(ref T lhs, ref T rhs) {
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}
static void Main(string[] args) {
int a, b;
char c, d;
a = 45;
b = 60;
c = 'K';
d = 'P';
Console.WriteLine("Int values before calling swap:");
Console.WriteLine("a = {0}, b = {1}", a, b);
Console.WriteLine("Char values before calling swap:");
Console.WriteLine("c = {0}, d = {1}", c, d);
Swap(ref a, ref b);
Swap(ref c, ref d);
Console.WriteLine("Int values after calling swap:");
Console.WriteLine("a = {0}, b = {1}", a, b);
Console.WriteLine("Char values after calling swap:");
Console.WriteLine("c = {0}, d = {1}", c, d);
Console.ReadKey();
}
}
} ผลลัพธ์
Int values before calling swap: a = 45, b = 60 Char values before calling swap: c = K, d = P Int values after calling swap: a = 60, b = 45 Char values after calling swap: c = P, d = K