C#의 익명 메서드를 사용하여 코드 블록을 C#의 대리자 매개변수로 전달합니다. 익명 메소드는 이름이 없고 본문만 있는 메소드입니다.
이것이 익명 메소드를 선언하는 방법입니다 -
delegate void DemoMethod(int n);
...
DemoMethod dm = delegate(int a) {
Console.WriteLine("Our Anonymous Method: {0}", a);
}; 위와 같이 익명 메서드의 본문은 다음과 같습니다. -
Console.WriteLine("Our Anonymous Method: {0}", a); 예시
C#에서 Anonymous 메소드를 구현하기 위해 다음 코드를 실행할 수 있습니다 −
using System;
delegate void Demo(int n);
namespace MyDelegate {
class TestDelegate {
static int num = 10;
public static void DisplayAdd(int p) {
num += p;
Console.WriteLine("Named Method: {0}", num);
}
public static void DisplayMult(int q) {
num *= q;
Console.WriteLine("Named Method: {0}", num);
}
public static int getNum() {
return num;
}
static void Main(string[] args) {
Demo dm = delegate(int x) {
Console.WriteLine("Anonymous Method: {0}", x);
};
//calling the delegate using the anonymous method
dm(15);
//instantiating the delegate using the named methods
dm = new Demo(DisplayAdd);
//calling the delegate using the named methods
dm(10);
//instantiating the delegate using another named methods
dm = new Demo(DisplayMult);
//calling the delegate using the named methods
dm(4);
Console.ReadKey();
}
}
} 출력
Anonymous Method: 15 Named Method: 20 Named Method: 80