The C# Programming Language, 4th Edtion
1.11 Delegate
delegate(델리게이트) 타입은 특정 파라미터 목록과 리턴 타입에 대한 참조를 나타낸다. 델리게이트는 메소드를 엔터티처럼 취급해서 변수에 할당하거나 파라미터로 넘길 수 있다. 다른 언어의 함수 포인터(function pointer)와 비슷해보이지만, (C#의)델리게이트는 객체 지향적이고 타입-안정적(type-safe)이다.
using system;
delegate double Function(double x);
class Multiplier
{
double factor;
public Multiplier(double factor)
{
this.factor = factor;
}
public double Multiply(double x)
{
return x * factor;
}
class Test
{
static double Square(double x)
{
return x * x;
}
static double[] Apply(double[] a, Function f)
{
double[] result = new double[a.Length];
for (int i = 0; i <a.Length; i++)
result[i] = f(a[i]);
return result;
}
static void Main()
{
double[] a = {0.0, 0.5, 1.0};
double[] squares = Apply(a, Square); // static method
double[] sines = Apply(a, Math.Sin); // static method
Multiplier m = new Multiplier(2.0);
double[] doubles = Apply(a, m.Multiply); // instance method
double[] dbls = Apply(a, x => x * 2.0); // anonymous functions
for (int i = 0; i < a.Length; i++)
Console.WriteLine("value: {0}", dbls[i]);
}
}
}