ㆍ람다식
- 델리게이트 매개변수를 지정
- 연산자: =>
- 종류 : 식람다( => ), 문람다 ( => {})
- 변수 타입 생략 가능
<예제>
using System;
class Ex
{
delegate int Plus(int a, int b);
delegate void Minus(int a, int b);
static void Main(string[] args)
{
// 식 람다
Plus sum = (a, b) => a + b;
int result = sum(10, 20);
Console.WriteLine(result);// 30
// 문 람다
Minus minus = (a, b) =>
{
int m = a - b;
Console.WriteLine(m);
};
minus(10, 20);
}
}
ㆍFunc<in T.... , out T>
- 결과를 반환하는 매서드 참조
- 맨 오른쪽에 있는게 반환 타입
using System;
class Ex
{
static void Main(string[] args)
{
// 기존 매서드 지정
Func<string, string> x = Result;
Console.WriteLine(x("TEST"));
// 무명 매서드 지정
Func<string, string, string> x2 = delegate (string a, string b)
{
return a + b;
};
Console.WriteLine(x2("TEST", "TEST2"));
// 람다 식
Func<int, string> x3 = y => { return y + "입니다."; };
Console.WriteLine(x3(123));
}
public static string Result(string s)
{
return s;
}
}
ㆍAction <in T...>
- 결과를 반환하지 않는 매서드 참조, 일련의 작업 수행이 목적
- 맨 오른쪽에 있는게 반환 타입
using System;
class Ex
{
static void Main(string[] args)
{
// 기존 매서드 지정
Action<string> x = Result;
x("TEST");
// 무명 매서드 지정
Action<string, string> x2 = delegate (string a, string b)
{
Console.WriteLine($"{a}, {b}");
};
x2("TEST", "TEST2");
// 람다 식
Action<int> x3 = y => Console.WriteLine($"{y}");
x3(123);
}
public static void Result(string s)
{
Console.WriteLine(s);
}
}
'C# > 공부기록' 카테고리의 다른 글
[C#] Linq / 시간 예제 (0) | 2023.01.14 |
---|---|
[C#] Linq / index, value (0) | 2023.01.14 |
[C#] Linq (0) | 2023.01.14 |
[C#] List<T> (0) | 2023.01.14 |
[C#] 어셈블리(assembly) (0) | 2023.01.14 |