Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1109. C# 10 - (11) Lambda 개선 [링크 복사], [링크+제목 복사],
조회: 8959
글쓴 사람
정성태 (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)
13088정성태6/27/20225636개발 환경 구성: 645. "Developer Command Prompt for VS 2022" 명령행 환경의 폰트를 바꾸는 방법
13087정성태6/23/20228651스크립트: 41. 파이썬 - FastAPI / uvicorn 호스팅 환경에서 asyncio 사용하는 방법 [1]
13086정성태6/22/20228079.NET Framework: 2026. C# 11 - 문자열 보간 개선 2가지파일 다운로드1
13085정성태6/22/20228149.NET Framework: 2025. C# 11 - 원시 문자열 리터럴(raw string literals)파일 다운로드1
13084정성태6/21/20226715개발 환경 구성: 644. Windows - 파이썬 2.7을 msi 설치 없이 구성하는 방법
13083정성태6/20/20227361.NET Framework: 2024. .NET 7에 도입된 GC의 메모리 해제에 대한 segment와 region의 차이점 [2]
13082정성태6/19/20226373.NET Framework: 2023. C# - Process의 I/O 사용량을 보여주는 GetProcessIoCounters Win32 API파일 다운로드1
13081정성태6/17/20226434.NET Framework: 2022. C# - .NET 7 Preview 5 신규 기능 - System.IO.Stream ReadExactly / ReadAtLeast파일 다운로드1
13080정성태6/17/20227059개발 환경 구성: 643. Visual Studio 2022 17.2 버전에서 C# 11 또는 .NET 7.0 preview 적용
13079정성태6/17/20224685오류 유형: 814. 파이썬 - Error: The file/path provided (...) does not appear to exist
13078정성태6/16/20226815.NET Framework: 2021. WPF - UI Thread와 Render Thread파일 다운로드1
13077정성태6/15/20227112스크립트: 40. 파이썬 - PostgreSQL 환경 구성
13075정성태6/15/20226055Linux: 50. Linux - apt와 apt-get의 차이 [2]
13074정성태6/13/20226386.NET Framework: 2020. C# - NTFS 파일에 사용자 정의 속성값 추가하는 방법파일 다운로드1
13073정성태6/12/20226623Windows: 207. Windows Server 2022에 도입된 WSL 2
13072정성태6/10/20226901Linux: 49. Linux - ls 명령어로 출력되는 디렉터리 색상 변경 방법
13071정성태6/9/20227519스크립트: 39. Python에서 cx_Oracle 환경 구성
13070정성태6/8/20227332오류 유형: 813. Windows 11에서 입력 포커스가 바뀌는 문제 [1]
13069정성태5/26/20229582.NET Framework: 2019. C# - .NET에서 제공하는 3가지 Timer 비교 [2]
13068정성태5/24/20228047.NET Framework: 2018. C# - 일정 크기를 할당하는 동안 GC를 (가능한) 멈추는 방법 [1]파일 다운로드1
13067정성태5/23/20227336Windows: 206. Outlook - 1년 이상 지난 메일이 기본적으로 안 보이는 문제
13066정성태5/23/20226677Windows: 205. Windows 11 - Windows + S(또는 Q)로 뜨는 작업 표시줄의 검색 바가 동작하지 않는 경우
13065정성태5/20/20227330.NET Framework: 2017. C# - Windows I/O Ring 소개 [2]파일 다운로드1
13064정성태5/18/20226927.NET Framework: 2016. C# - JIT 컴파일러의 인라인 메서드 처리 유무
13063정성태5/18/20227356.NET Framework: 2015. C# - 인라인 메서드(inline methods)
13062정성태5/17/20228096.NET Framework: 2014. C# - async/await 그리고 스레드 (4) 비동기 I/O 재현파일 다운로드1
... 16  17  18  19  20  21  [22]  23  24  25  26  27  28  29  30  ...