//1. 대리자 선언
delegate int Calculate(int a, int b);
static void Main(string[] args)
{
//2. delegate 타입의 참조변수에 익명메소드를 참조(delegate 인스턴스화)
Calculate Cal = (int a, int b) => a+b;
//3. delegate 호출
cal(10, 20)
}
//1. 대리자 선언
delegate int Calculate(int a, int b);
static void Main(string[] args)
{
//2. delegate 타입의 참조변수에 익명메소드를 참조(delegate 인스턴스화)
Calculate Cal = (int a, int b) => {
int sum = a+b;
Console.Write(sum);
}
//3. delegate 호출
cal(10, 20)
}
그러나 매번 delegate 변수를 선언해서 참조하여 사용할 수 는 없는 노릇
그래서 사용되는 Func와 Action delegate가 있다.
Func는 반환값(return)이 있는 메소드를 참조
Action은 반환값(return)이 없는 메소드를 참조
.Net 프레임워크에는 17개 Func Delegate가 준비되어있음
Func<float> func() = () => 0.1f;
//Func의 선언을 보면 아래의 경우 인자는 3개 리턴변수 1개 총 4개의 파라미터를 받는것 처럼 보인다.
//하지만 실제로 사용할 경우 3개의 인자만 사용하면 된다.
public delegate TResult Func<in T1, in T2, in T3, out TResult>(T1 arg1, T2 arg2, T3 arg3);
Func<float> func1 = () => 0.1f;
Func<int, int, int, int> tripleMultiply = (a, b, c) => a* b *c;
Console.WriteLine("print func1() : "+ func1());
Console.WriteLine("print tripleMultiply() : " + tripleMultiply(1,2,3));
Func, Action의 3가지 사용방법
static void temp(string name)
{
Console.WriteLine("name : {0}", name);
}
static void Main(string[] args)
{
//1. 파라미터 없이 사용
Action action1 = () => Console.WriteLine("action 1");
//2. 기존 생성된 함수를 참조지정
Action<string> action2 = new Action<string>(temp);
//3. 다수의 인자를 받아 사용
Action<string, string> action3 = (name, age) =>
{
Console.WriteLine("name : {0}, age : {1}", name, age);
};
}