아카이빙/C#

[C#] 람다식 (Lambda Expression)

셩님 2018. 6. 26. 14:19

[C#] 람다식 (Lambda Expression)

  • 람다식은 익명 메소드를 만드는 하나의 방법이다. (또 다른 방법은 delegate를 이용)

  • 보다 분명하고 간결한 방법으로 함수를 묘사하기 위함

기본 람다식의 형식

delegate int Del(int a, int b);
static void Main()
{
   //매개변수목록 => 식
   Del d1 = (int a, int b) => a + b;
   Console.WriteLine(d1(5, 8));

   //형식 유추(Type Inference)
   Del d2 = (a, b) => a + b;
   Console.WriteLine(d2(5, 8));
}

문 형식의 람다식 (Statement Lambda)

delegate void DoSomething();
static void Main()
{
   DoSomething DoIt = () =>
  {
       Console.WriteLine("a");
       Console.WriteLine("b");
       Console.WriteLine("c");  
  };

   DoIt();
}

Func와 Action으로 간편히 익명 메소드 만들기

  • 앞서 예를들었던 익명 메소드를 만들기 위해서는 별개의 델리게이트 선언이 필요했다.

  • 이 문제를 해결하기 위해 마이크로소프트는 .NET 프레임워크에 Func와 Action 델리게이트를 미리 선언해두었다.

  • Func 델리게이트는 결과를 반환하는 메소드를 참조

  • Action 델리게이트는 결과를 반환하지 않는 메소드를 참조

1) Func Delegate

static void Main()
{
   //입력 매개변수 형식 1,2는 int 반환 형식도 int
   Func<int, int, int> Add = (x, y) => x + y;

   Console.WriteLine(Add(5, 8));
}

2) Action Delegate

static void Main()
{
   Action<int, int> Add = (x, y) => Console.WriteLine(x + y);
   Add(5, 8);
}
  • Action Delegate는 반환형식이 없다.

참조

  • 뇌를 자극하는 C# 5.0 프로그래밍, 박상현, 한빛미디어


'아카이빙 > C#' 카테고리의 다른 글

[Effective C#] string.Format()을 보간 문자열로 대체하라  (0) 2018.06.30
[C#] LINQ  (0) 2018.06.26
[C#] 이벤트와 델리게이트  (0) 2018.06.25
[C#] Delegate와 익명메소드  (0) 2018.06.25
[C#] Delegate는 언제 사용하는가  (0) 2018.06.25