Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1109. C# 10 - (11) Lambda 개선 [링크 복사], [링크+제목 복사]
조회: 8786
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 15개 있습니다.)
.NET Framework: 1094. C# 10 - (1) 구조체를 생성하는 record struct
; https://www.sysnet.pe.kr/2/0/12790

.NET Framework: 1096. C# 10 - (2) 전역 네임스페이스 선언
; https://www.sysnet.pe.kr/2/0/12792

.NET Framework: 1097. C# 10 - (3) 개선된 변수 초기화 판정
; https://www.sysnet.pe.kr/2/0/12793

.NET Framework: 1099. C# 10 - (4) 상수 문자열에 포맷 식 사용 가능
; https://www.sysnet.pe.kr/2/0/12796

.NET Framework: 1100. C# 10 - (5) 속성 패턴의 개선
; https://www.sysnet.pe.kr/2/0/12799

.NET Framework: 1101. C# 10 - (6) record class 타입의 ToString 메서드를 sealed 처리 허용
; https://www.sysnet.pe.kr/2/0/12801

.NET Framework: 1103. C# 10 - (7) Source Generator V2 APIs
; https://www.sysnet.pe.kr/2/0/12804

.NET Framework: 1104. C# 10 - (8) 분해 구문에서 기존 변수의 재사용 가능
; https://www.sysnet.pe.kr/2/0/12805

.NET Framework: 1105. C# 10 - (9) 비동기 메서드가 사용할 AsyncMethodBuilder 선택 가능
; https://www.sysnet.pe.kr/2/0/12807

.NET Framework: 1108. C# 10 - (10) 개선된 #line 지시자
; https://www.sysnet.pe.kr/2/0/12812

.NET Framework: 1109. C# 10 - (11) Lambda 개선
; https://www.sysnet.pe.kr/2/0/12813

.NET Framework: 1113. C# 10 - (12) 문자열 보간 성능 개선
; https://www.sysnet.pe.kr/2/0/12826

.NET Framework: 1114. C# 10 - (13) 단일 파일 내에 적용되는 namespace 선언
; https://www.sysnet.pe.kr/2/0/12828

.NET Framework: 1115. C# 10 - (14) 구조체 타입에 기본 생성자 정의 가능
; https://www.sysnet.pe.kr/2/0/12829

.NET Framework: 1116. C# 10 - (15) CallerArgumentExpression 특성 추가
; https://www.sysnet.pe.kr/2/0/12835




C# 10 - (11) Lambda 개선

C# 10부터 3가지 부분에서 람다 사용법에 대한 개선이 이뤄졌습니다.

  1. 람다 식에 특성 사용
  2. 반환 타입 지정 허용
  3. 람다 식에 대한 추론 향상

하나씩 살펴볼까요? ^^

이미 C# 9.0부터 로컬 함수에 특성을 허용함으로써 다음과 같은 표현이 가능했는데요,

using System;

GetName();

[Obsolete]
string GetName() => "Anders";

이제는 람다 식 자체에도 특성을 지정할 수 있게 되었습니다.

using System.Diagnostics;
using System.Runtime.InteropServices;

var list = new List<string> { "Anders", "Kevin" };

// 람다 식에 특성 허용
list.ForEach([DebuggerHidden] (elem) => Console.WriteLine(elem));
// 매개 변수에도 특성 허용
list.ForEach(([CustomAttr] elem) => Console.WriteLine(elem));

Func<int> f1 =[return: MarshalAs(UnmanagedType.Bool)] () => 1;
Func<int> f2 =[return: CustomAttrAttribute] () => { return 1; };

Func<int, int> f3 =[return: CustomAttrAttribute] (arg) => { return arg + 1; };
// 특성을 적용하는 경우, 인자에 대한 괄호를 지정하지 않으면 컴파일 에러
// Error CS8916 Attributes on lambda expressions require a parenthesized parameter list.
// Func<int, int> f4 =[return: CustomAttrAttribute] arg => arg + 1;;
// Func<int, int> f4 =[return: CustomAttrAttribute] static arg => { return arg + 1; };

// AttributeTargets.Method가 지정된 특성은 람다 식에 적용 가능하지만,
// Conditional 특성은 예외적으로 람다 식에 적용하면 컴파일 에러
// error CS0577: The Conditional attribute is not valid on 'lambda expression' because it is a constructor, destructor, operator, lambda expression, or explicit interface implementation
// Action<int, int> f4 = ([Conditional("DEBUG")] static (x, y) => Debug.Assert(x == y));

public class CustomAttrAttribute : Attribute
{
}




그다음, 반환 타입에 대한 명시적인 지정을 허용하면서 다음의 표현들이 가능하게 바뀌었습니다.

// 람다 식에 반환값 명시
{
    Func<int, short> f1 = short (x) => 1;

    // 특성과 마찬가지로 반환 타입을 지정한 경우, 매개변수에 대한 괄호를 지정하지 않으면 컴파일 에러
    // error CS1525: Invalid expression term 'short'
    // Func<int, short> f = short x => 1;

    MethodRefDelegate f2 = (ref int (ref int x) => ref x);

    // ref 반환 타입의 경우 괄호가 없으면 컴파일 오류
    // error CS8171: Cannot initialize a by-value variable with a reference
    // MethodRefDelegate f = ref int (ref int x) => ref x;

    int number = 5;
    f2(ref number) = 10;
    Console.WriteLine($"number == {number}");

    Action<int> f3 = static void (_) => { };
}

public delegate ref int MethodRefDelegate(ref int arg);

public class MyType<T>
{
    public void Print()
    {
        Func<T> f = T () => default;
        Console.WriteLine($"T Result: {f()}");
    }
}

참고로 위에서 ref 반환 타입의 경우 괄호를 (현재는?) 명시해야만 컴파일이 되는데요, 이에 대해 문서에서 다음과 같이 언급하고 있습니다.

The parser should allow ref return types in assignment without parentheses.

Delegate d1 = (ref int () => x); // ok

// Visual Studio 2022 preview 3.1에서는 컴파일 오류
Delegate d2 = ref int () => x;   // ok

아마도 마지막 버전에서는 개선이 될지 지켜봐야겠습니다. ^^
(2022-07-12 업데이트: 현재 괄호 없이 컴파일 가능)




그리고, 마침내 람다 식에 대해서도 타입 추론이 적용되었습니다. 사실, 위에서 설명한 특성 지정이나 반환값 명시는 다소 특수한 경우여서 그다지 쓸 일이 많지는 않은데요, 반면 람다 식의 타입 추론은 꽤나 자주 쓸 수 있는 기능입니다.

이로 인해, 위에서 지금까지 실습했던 내용들에 대해 모두 "var"를 이용해 변수로 받는 것이 가능합니다.

// 타입 추론
{
    var f1 =[return: MarshalAs(UnmanagedType.Bool)] () => 1;
    var f2 =[return: CustomAttrAttribute] () => { return 1; };
    var f3 = short (int x) => 1;
    var f4 = (ref int (ref int x) => ref x);
    var f5 =[return: CustomAttrAttribute] (int arg) => { return arg + 1; };
}

물론, 위의 추론이 가능하려면 컴파일러에게 충분한 정보를 제공해야 합니다. 가령, 다음의 경우는 각각 모호한 부분이 있어 컴파일 오류가 발생하지만,

// 컴파일 오류 - error CS8917: The delegate type could not be inferred.
var f1 = () => default; // 반환 타입의 모호
var f2 = (x) => { }; // 매개 변수 타입의 모호
var f3 = x => x; // 반환 및 매개 변수 타입의 모호

사용자가 그에 따른 정보를 명시해 주면 정상적으로 추론이 이뤄지므로 컴파일이 잘 됩니다.

var f1 = int () => default; // 반환 타입 명시
var f2 = (int x) => { }; // 매개 변수 타입 명시
var f3 = (int x) => x; // 매개 변수의 타입이 명시됨으로써 반환 타입까지 추론

그러니까, 따지고 보면 C# 10에 추가된 "람다 식의 반환 타입 지정 허용"은 결국 타입 추론을 마무리하기 위한 목적에서도 필요했을 기능입니다.

그런데, 이것 역시 아직 Preview 단계여서 그런지 문서의 내용과 맞지 않는 부분들이 좀 있습니다. 가령, 다음의 코드는,

var fs = new[] { (string s) => s.Length, (string s) => int.Parse(s) } // Func<string, int>[]

분위기로 보아 배열 요소가 Func<string, int> 타입으로 추론될 것이므로 컴파일이 될 것처럼 나오지만 실제로는 오류가 발생합니다. 그래서 다음과 같이 (아직은?) 명시를 해야만 합니다.

var fs = new Func<string, int>[] { (string s) => s.Length, (string s) => int.Parse(s) };

또한 아래의 예제 코드도,

public static class MyEtension
{
    static void F1() { }

    public static void F1<T>(this T t) { }

    static void F2(this string s) { }

    public static void Write()
    {
        var f6 = F1; // F1 메서드와 F1<T> 중 어느 것을 선택해야 할지 알 수 없으므로 당연히 컴파일 오류
                     // error CS8917: The delegate type could not be inferred.

        // 문서에서는 System.Action으로 추론한다고 되어 있지만 실제로는 컴파일 오류
        // error CS8917: The delegate type could not be inferred.
        var f7 = "".F1;

        // 정상적으로 System.Action<string> 형식으로 추론
        var f8 = F2;
    }
}

문서와는 다르게 f7에 대해 컴파일 오류가 발생합니다.

이와 함께 타입 추론이 개선되어야 한다는 식의 언급도 있습니다.

Method type inference should make an exact inference from an explicit lambda return type.

static void F<T>(Func<T, T> f) { ... }
F(int (i) => i); // Func<int, int>

즉, 위의 코드에서 F(...) 호출의 람다식이 Func<int, int>로 추론되어야 한다고 설명은 하지만 아직도 이 코드는 "error CS0411: The type arguments for method 'F(Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly."라는 컴파일 오류가 발생합니다.




마지막으로, 결국 람다 식의 타입 추론이 가능하기 때문에, 명시적인 인스턴스를 생성하지 않고 직접 호출하는 것도 가능하므로 이에 대해 다음과 같은 "may be" 언급을 하고 있습니다.

Lambda expressions may be invoked directly. The compiler will generate a call to the underlying method without generating a delegate instance or synthesizing a delegate type. Directly invoked lambda expressions do not require explicit parameter types.


그래서 이렇게 호출하는 것도 가능할 거라고 하는데,

int zero = ((int x) => x)(0); // ok
int one = (x => x)(1);        // ok

아직은 아닙니다. ^^

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




C# 10 - (1) 구조체를 생성하는 record struct (공식 문서, Static Abstract Members In Interfaces C# 10 Preview)
; https://www.sysnet.pe.kr/2/0/12790

C# 10 - (2) 전역 네임스페이스 선언 (공식 문서, Global Using Directive)
; https://www.sysnet.pe.kr/2/0/12792

C# 10 - (3) 개선된 변수 초기화 판정 (공식 문서, Improved Definite Assignment)
; https://www.sysnet.pe.kr/2/0/12793

C# 10 - (4) 상수 문자열에 포맷 식 사용 가능 (공식 문서, Constant Interpolated Strings)
; https://www.sysnet.pe.kr/2/0/12796

C# 10 - (5) 속성 패턴의 개선 (공식 문서, Extended property patterns)
; https://www.sysnet.pe.kr/2/0/12799

C# 10 - (6) record class 타입의 ToString 메서드를 sealed 처리 허용 (공식 문서, Sealed record ToString)
; https://www.sysnet.pe.kr/2/0/12801

C# 10 - (7) Source Generator V2 APIs (Source Generator V2 APIs)
; https://www.sysnet.pe.kr/2/0/12804

C# 10 - (8) 분해 구문에서 기존 변수의 재사용 가능 (공식 문서, Mix declarations and variables in deconstruction)
; https://www.sysnet.pe.kr/2/0/12805

C# 10 - (9) 비동기 메서드가 사용할 AsyncMethodBuilder 선택 가능 (공식 문서, Async method builder override); 
; https://www.sysnet.pe.kr/2/0/12807

C# 10 - (10) 개선된 #line 지시자 (공식 문서, Enhanced #line directive)
; https://www.sysnet.pe.kr/2/0/12812

C# 10 - (11) Lambda 개선 (공식 문서 1, 공식 문서 2, Lambda improvements) 
; https://www.sysnet.pe.kr/2/0/12813

C# 10 - (12) 문자열 보간 성능 개선 (공식 문서, Interpolated string improvements)
; https://www.sysnet.pe.kr/2/0/12826

C# 10 - (13) 단일 파일 내에 적용되는 namespace 선언 (공식 문서, File-scoped namespace)
; https://www.sysnet.pe.kr/2/0/12828

C# 10 - (14) 구조체 타입에 기본 생성자 정의 가능 (공식 문서, Parameterless struct constructors)
; https://www.sysnet.pe.kr/2/0/12829

C# 10 - (15) CallerArgumentExpression 특성 추가 (공식 문서, Caller expression attribute)
; https://www.sysnet.pe.kr/2/0/12835

Language Feature Status
; https://github.com/dotnet/roslyn/blob/main/docs/Language%20Feature%20Status.md




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/14/2022]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13227정성태1/23/20234871개발 환경 구성: 659. Windows - IP MTU 값을 바꿀 수 있을까요? [1]
13226정성태1/23/20234547.NET Framework: 2088. .NET 5부터 지원하는 GetRawSocketOption 사용 시 주의할 점
13225정성태1/21/20233801개발 환경 구성: 658. Windows에서 실행 중인 소켓 서버를 다른 PC 또는 WSL에서 접속할 수 없는 경우
13224정성태1/21/20234144Windows: 221. Windows - Private/Public/Domain이 아닌 네트워크 어댑터 단위로 방화벽을 on/off하는 방법
13223정성태1/20/20234342오류 유형: 838. RDP 연결 오류 - The two computers couldn't connect in the amount of time allotted
13222정성태1/20/20233999개발 환경 구성: 657. WSL - DockerDesktop.vhdx 파일 위치를 옮기는 방법
13221정성태1/19/20234233Linux: 57. C# - 리눅스 프로세스 메모리 정보파일 다운로드1
13220정성태1/19/20234370오류 유형: 837. NETSDK1045 The current .NET SDK does not support targeting .NET ...
13219정성태1/18/20233932Windows: 220. 네트워크의 인터넷 접속 가능 여부에 대한 판단 기준
13218정성태1/17/20233871VS.NET IDE: 178. Visual Studio 17.5 (Preview 2) - 포트 터널링을 이용한 웹 응용 프로그램의 외부 접근 허용
13217정성태1/13/20234461디버깅 기술: 185. windbg - 64비트 운영체제에서 작업 관리자로 뜬 32비트 프로세스의 덤프를 sos로 디버깅하는 방법
13216정성태1/12/20234716디버깅 기술: 184. windbg - 32비트 프로세스의 메모리 덤프인 경우 !peb 명령어로 나타나지 않는 환경 변수
13215정성태1/11/20236261Linux: 56. 리눅스 - /proc/pid/stat 정보를 이용해 프로세스의 CPU 사용량 구하는 방법 [1]
13214정성태1/10/20235824.NET Framework: 2087. .NET 6부터 SourceGenerator와 통합된 System.Text.Json [1]파일 다운로드1
13213정성태1/9/20235367오류 유형: 836. docker 이미지 빌드 시 "RUN apt install ..." 명령어가 실패하는 이유
13212정성태1/8/20235121기타: 85. 단정도/배정도 부동 소수점의 정밀도(Precision)에 따른 형변환 손실
13211정성태1/6/20235147웹: 42. (https가 아닌) http 다운로드를 막는 웹 브라우저
13210정성태1/5/20234202Windows: 219. 윈도우 x64의 경우 0x00000000`7ffe0000 아래의 주소는 왜 사용하지 않을까요?
13209정성태1/4/20234092Windows: 218. 왜 윈도우에서 가상 메모리 공간은 64KB 정렬이 된 걸까요?
13208정성태1/3/20234053.NET Framework: 2086. C# - Windows 운영체제의 2MB Large 페이지 크기 할당 방법파일 다운로드1
13207정성태12/26/20224355.NET Framework: 2085. C# - gpedit.msc의 "User Rights Assignment" 특권을 코드로 설정/해제하는 방법파일 다운로드1
13206정성태12/24/20224580.NET Framework: 2084. C# - GetTokenInformation으로 사용자 SID(Security identifiers) 구하는 방법 [3]파일 다운로드1
13205정성태12/24/20224934.NET Framework: 2083. C# - C++과의 연동을 위한 구조체의 fixed 배열 필드 사용 (2)파일 다운로드1
13204정성태12/22/20224221.NET Framework: 2082. C# - (LSA_UNICODE_STRING 예제로) CustomMarshaler 사용법파일 다운로드1
13203정성태12/22/20224381.NET Framework: 2081. C# Interop 예제 - (LSA_UNICODE_STRING 예제로) 구조체를 C++에 전달하는 방법파일 다운로드1
13202정성태12/21/20224792기타: 84. 직렬화로 설명하는 Little/Big Endian파일 다운로드1
... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...