제네릭을 사용하면 모든 데이터 유형에서 작동할 수 있는 클래스 또는 메서드를 작성할 수 있습니다. 유형 매개변수를 사용하여 일반 메소드 선언 -
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