40.4 무명 메서드
무명 메서드(anonymous method)는 익명 메서드라고도 하며, 단어 그대로 이름이 없는 메서드입니다. 이번에는 무명 메서드를 사용해 보겠습니다. 다음 내용을 입력한 후 실행해 보세요.
무명 메서드 사용: AnonymousMethod.cs
using System;
namespace AnonymousMethod
{
public class Print
{
public static void Show(string msg) => Console.WriteLine(msg);
}
public class AnonymousMethod
{
//대리자 선언
public delegate void PrintDelegate(string msg);
public delegate void SumDelegate(int a, int b);
static void Main()
{
//① 메서드 직접 호출
Print.Show("안녕하세요.");
//② 대리자에 메서드 등록 후 호출
PrintDelegate pd = new PrintDelegate(Print.Show);
pd("반갑습니다.");
//③ 무명(익명) 메서드로 호출: delegate 키워드로 무명 메서드 생성
PrintDelegate am = delegate (string msg)
{
Console.WriteLine(msg);
};
am("또 만나요.");
//④ 무명 메서드 생성 및 호출
SumDelegate sd = delegate (int a, int b) { Console.WriteLine(a + b); };
sd(3, 5); //8
}
}
}