728x90
반응형
using System;
void Foo<T>(T x) { }
void Bar<T>(Action<T> a) { }
//Bar (x => Foo (x)); // What type is x?
Bar((int x) => Foo(x)); // fix
Bar<int>(x => Foo(x)); // Specify type parameter for Bar
Bar<int>(Foo); // As above, but with method group;
using System;
int cnt = 0;
Func<int> test = () => cnt++;
Console.WriteLine(test()); // 0
Console.WriteLine(test()); // 1
Console.WriteLine(cnt); // 2
int factor = 2;
Func<int, int> multiplier = n => n * factor;
factor = 10;
Console.WriteLine(multiplier(3)); // 30
using System;
Func<int> test = Test();
Console.WriteLine(test()); // 0
Console.WriteLine(test()); // 1
static Func<int> Test() // 반환형이 델리게이트
{
int cnt = 0;
return () => cnt++; // 리턴은 메서드여야 하는데 람다식으로 대체
}
using System;
//Func<int, int> multiplier = static n => n * 2;
int factor = 2;
Func<int, int> multiplier = static n => n * factor; // will not compile
Console.WriteLine(multiplier(3)); // 6
* 부작용이 있는지 확인하려 할 때 static을 붙여서 사용하면 된다(제대로 이해한 게 맞는지 파악이 안됨)
728x90
반응형
'C#' 카테고리의 다른 글
C# 람다 Case4 ETC (이벤트 체인에 무명함수 연결) (0) | 2021.12.14 |
---|---|
C# 람다 Case 3 - list.sort로 정렬하기 (0) | 2021.12.14 |
C# 람다 Case1 - 기본 단순하게 사용, 리턴값 없이 단순 구문으로 사용 (0) | 2021.12.14 |
.NET C#에서 리플렉션을 사용하여 생성자를 동적으로 호출 (0) | 2021.12.14 |
C# string null, 공백 체크 (0) | 2021.12.13 |
댓글