익명 메서드는 코드 블록을 대리자 매개변수로 전달하는 기술을 제공합니다. 익명 메소드는 이름이 없고 본문만 있는 메소드입니다.
C#에서 Anonymous 메서드를 선언하는 방법을 살펴보겠습니다 −
delegate void NumberChanger(int n);
...
NumberChanger nc = delegate(int x) {
Console.WriteLine("Anonymous Method: {0}", x);
}; 예시
다음은 C#에서 Anonymous 메서드를 구현하는 예입니다.
using System;
delegate void NumberChanger(int n);
namespace DelegateAppl {
class Demo {
static int num = 10;
public static void AddNum(int p) {
num += p;
Console.WriteLine("Named Method: {0}", num);
}
public static void MultNum(int q) {
num *= q;
Console.WriteLine("Named Method: {0}", num);
}
public static int getNum() {
return num;
}
static void Main(string[] args) {
//create delegate instances using anonymous method
NumberChanger nc = delegate(int x) {
Console.WriteLine("Anonymous Method: {0}", x);
};
//calling the delegate using the anonymous method
nc(10);
//instantiating the delegate using the named methods
nc = new NumberChanger(AddNum);
//calling the delegate using the named methods
nc(5);
//instantiating the delegate using another named methods
nc = new NumberChanger(MultNum);
//calling the delegate using the named methods
nc(2);
Console.ReadKey();
}
}
} 출력
Anonymous Method: 10 Named Method: 15 Named Method: 30