Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1109. C# 10 - (11) Lambda 개선 [링크 복사], [링크+제목 복사]
조회: 8746
글쓴 사람
정성태 (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)
13549정성태2/3/20242473개발 환경 구성: 706. C# - 컨테이너에서 실행하기 위한 (소켓) 콘솔 프로젝트 구성
13548정성태2/1/20242306개발 환경 구성: 705. "Docker Desktop for Windows" - ASP.NET Core 응용 프로그램의 소켓 주소 바인딩(IPv4/IPv6 loopback, Any)
13547정성태1/31/20242054개발 환경 구성: 704. Visual Studio - .NET 8 프로젝트부터 dockerfile에 추가된 "USER app" 설정
13546정성태1/30/20241894Windows: 255. (디버거의 영향 등으로) 대상 프로세스가 멈추면 Socket KeepAlive로 연결이 끊길까요?
13545정성태1/30/20241825닷넷: 2212. ASP.NET Core - 우선순위에 따른 HTTP/HTTPS 호스트:포트 바인딩 방법
13544정성태1/30/20241846오류 유형: 894. Microsoft.Data.SqlClient - Could not load file or assembly 'System.Security.Permissions, ...'
13543정성태1/30/20241822Windows: 254. Windows - 기본 사용 중인 5357 포트 비활성화는 방법
13542정성태1/30/20241875오류 유형: 893. Visual Studio - Web Application을 실행하지 못하는 IISExpress - 두 번째 이야기
13541정성태1/29/20241919VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20242049Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20242143개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20242212닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/20242258닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/20242370닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/20242200닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242030닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/20242223닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/20242134닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242019닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242009닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20241893닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242029Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20241957오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242045닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242011오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242063오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...