Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1109. C# 10 - (11) Lambda 개선 [링크 복사], [링크+제목 복사]
조회: 8748
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13598정성태4/16/2024210닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드1
13597정성태4/15/2024293닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/2024511닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/2024527닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/2024755닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/2024948닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241186C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241155닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241069Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241132닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241185닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신파일 다운로드1
13587정성태3/27/20241135오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241265Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241089Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241044개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241145Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241218Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241366개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241131닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241493오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241620닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241850닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241539닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20241662닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/20241552닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...