익명 메소드는 이름이 없는 메소드입니다. 이러한 메서드는 코드 블록을 대리자 매개변수로 전달하는 기술을 제공합니다.
익명 메서드는 delegate 키워드를 사용하여 대리자 인스턴스 생성과 함께 선언됩니다.
예시
using System;
delegate void Demo(int n);
namespace DelegateAppl {
class TestDelegate {
static int num = 50;
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
Demo d = delegate(int x) {
Console.WriteLine("Anonymous Method: {0}", x);
};
//calling the delegate using the anonymous method
d(100);
//instantiating the delegate using the named methods
d = new Demo(AddNum);
//calling the delegate using the named methods
d(5);
//instantiating the delegate using another named methods
d = new Demo(MultNum);
//calling the delegate using the named methods
d(2);
Console.ReadKey();
}
}
} 출력
Anonymous Method: 100 Named Method: 55 Named Method: 110
다음은 우리의 익명 방법입니다.
Demo d = delegate(int x) {
Console.WriteLine("Anonymous Method: {0}", x);
};