Programming/C#
[Programming/C#] 일반화 대리자
scii
2020. 9. 22. 20:37
대리자는 보통의 메소드뿐 아니라 일반화 메소드도 참조할 수 있다. 물론 이 경우에는 대리자도 일반화 메소드를 참조할 수 있도록 형식 매개 변수를 이용하여 선언되어야 한다. 형식 매개 변수를 이용해서 대리자를 선언하는 요령은 메소드와 같다. 괄호 <> 사이에 형식 매개 변수를 넣어주면 된다.
일반화 대리자 예제
using System;
namespace test
{
delegate int Compare<T>(T a, T b);
internal class Program
{
static int AscendCompare<T>(T a, T b) where T: IComparable<T>
{
return a.CompareTo(b);
}
static int DescendCompare<T>(T a, T b) where T : IComparable<T>
{
return b.CompareTo(a);
}
static void BubbleSort<T>(T[] array, Compare<T> comparer)
{
T temp;
for (int i = 0; i < array.Length - 1; i++)
{
for (int j = 0; j < (array.Length - (i + 1)); j++)
{
if (comparer(array[j], array[j+1]) > 0)
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
public static void Main(string[] args)
{
int[] array = new int[] {5, 3, 7, 1, 2};
BubbleSort<int>(array, new Compare<int>(AscendCompare));
for (int i = 0; i < array.Length; i++)
{
Console.Write($"{array[i]} ");
}
Console.WriteLine();
string[] array2 = {"abc", "def", "ghi", "jkl", "mno"};
BubbleSort<string>(array2, new Compare<string>(DescendCompare));
for (int i = 0; i < array2.Length; i++)
{
Console.Write($"{array2[i]} ");
}
Console.WriteLine();
}
}
}
/* 결과
1 2 3 5 7
mno jkl ghi def abc
*/
System.Int32(int), System,Double(double)을 비롯한 모든 수치 형식과 System.String(string)은 모두 IComparable을 상속하여 CompareTo() 메소드를 구현하고 있다.