Microsoft MVP성태의 닷넷 이야기
.NET Framework: 2037. C# 11 - 목록 패턴(List patterns) [링크 복사], [링크+제목 복사],
조회: 8621
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 18개 있습니다.)
.NET Framework: 1110. C# 11 - 인터페이스 내에 정적 추상 메서드 정의 가능 (DIM for Static Members)
; https://www.sysnet.pe.kr/2/0/12814

.NET Framework: 1118. C# 11 - 제네릭 타입의 특성 적용
; https://www.sysnet.pe.kr/2/0/12839

.NET Framework: 1182. C# 11  - ref struct에 ref 필드를 허용
; https://www.sysnet.pe.kr/2/0/13015

.NET Framework: 2025. C# 11  - 원시 문자열 리터럴(raw string literals)
; https://www.sysnet.pe.kr/2/0/13085

.NET Framework: 2026. C# 11 - 문자열 보간 개선 2가지
; https://www.sysnet.pe.kr/2/0/13086

.NET Framework: 2030. C# 11 - UTF-8 문자열 리터럴
; https://www.sysnet.pe.kr/2/0/13096

.NET Framework: 2031. C# 11 - 사용자 정의 checked 연산자
; https://www.sysnet.pe.kr/2/0/13099

.NET Framework: 2032. C# 11 - shift 연산자 재정의에 대한 제약 완화 (Relaxing Shift Operator)
; https://www.sysnet.pe.kr/2/0/13100

.NET Framework: 2035. C# 11 - 새로운 연산자 ">>>" (Unsigned Right Shift)
; https://www.sysnet.pe.kr/2/0/13110

.NET Framework: 2036. C# 11 - IntPtr/UIntPtr과 nint/nuint의 통합
; https://www.sysnet.pe.kr/2/0/13111

.NET Framework: 2037. C# 11 - 목록 패턴(List patterns)
; https://www.sysnet.pe.kr/2/0/13112

.NET Framework: 2038. C# 11 - Span 타입에 대한 패턴 매칭 (Pattern matching on ReadOnlySpan<char>)
; https://www.sysnet.pe.kr/2/0/13113

.NET Framework: 2042. C# 11 - 파일 범위 내에서 유효한 타입 정의 (File-local types)
; https://www.sysnet.pe.kr/2/0/13117

.NET Framework: 2045. C# 11 - 메서드 매개 변수에 대한 nameof 지원
; https://www.sysnet.pe.kr/2/0/13122

.NET Framework: 2046. C# 11 - 멤버(속성/필드)에 지정할 수 있는 required 예약어 추가
; https://www.sysnet.pe.kr/2/0/13123

.NET Framework: 2048. C# 11 - 구조체 필드의 자동 초기화(auto-default structs)
; https://www.sysnet.pe.kr/2/0/13125

.NET Framework: 2049. C# 11 - 정적 메서드에 대한 delegate 처리 시 cache 적용
; https://www.sysnet.pe.kr/2/0/13126

.NET Framework: 2102. C# 11 - ref struct/ref field를 위해 새롭게 도입된 scoped 예약어
; https://www.sysnet.pe.kr/2/0/13276




C# 11 - 목록 패턴(List patterns)

아래의 글에 보면,

C# 11 Preview: List patterns
; https://devblogs.microsoft.com/dotnet/early-peek-at-csharp-11-features/#c-11-preview-list-patterns

C# 11에 새롭게 추가한 목록 패턴 매칭을 소개합니다. 정말이지, 마이크로소프트가 C#의 패턴 매칭에 진심이군요. ^^ 처음 도입된 C# 7 이후로 꾸준히 패턴 매칭 문법을 보완하더니,

C# 7 - 기본 패턴 매칭 기능 추가
C# 8 - switch 식, 속성 패턴, 튜플 패턴, 위치 패턴 추가
C# 9 - "Type Patterns", "Relational Patterns", "Pattern Combinators", "Parenthesized Patterns" 추가
C# 10 - 속성 패턴 개선

C# 11에는 또다시 목록 패턴까지 추가했습니다. 간단하게 코드 먼저 볼까요? ^^

int[] arr1 = { 1, 2, 10 };
int[] arr2 = { 1, 2, 5, 10 };
int[] arr3 = { 1, 2, 5, 6, 7, 8, 9, 10 };

int[] arr4 = { 1, 3 };
int[] arr5 = { 1, 3, 6 };
int[] arr6 = { 2, 3 };

Console.WriteLine(CheckSwitch(arr1)); // 1
Console.WriteLine(CheckSwitch(arr2)); // 1
Console.WriteLine(CheckSwitch(arr3)); // 1

Console.WriteLine(CheckSwitch(arr4)); // 2
if (arr5 is [1, ..])
{
    Console.WriteLine(3); // 3
}
Console.WriteLine(CheckSwitch(arr6)); // 50

static int CheckSwitch(int[] values)
    => values switch
    {
        [1, 2, .., 10] => 1,
        [1, _] => 2,
        [1, ..] => 3,
        [..] => 50
    };

보시면, 목록의 패턴 매칭을 돕기 위해 그 자체에 슬라이스 패턴(..)과 무시 패턴(_)을 함께 제공하고 있습니다. 단지, switch 식의 경우엔 is와는 달리 그 특성상 "default" 경우를 위해 단독 슬라이스 패턴인 "[..]"을 마지막에 하나 제공해야 한다는 정도의 (없으면 경고를 주는) 추가 규칙이 있습니다.

List<int> list1 = new List<int>(new[] { 1, 3 });
Console.WriteLine(CheckSwitch(list1)); // 3

static int CheckSwitch(int[] values)
    => values switch
    {
        [1, 2, .., 10] => 1,
        [1, _] => 2,
        [1, ..] => 3,
        [..] => 50 // 없으면 warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive).
    };

static int CheckSwitch(List<int> values)
    => values switch
    {
        [1, 2] => 1,
        [1, _] => 2,
        [..] => 3, // 없으면 warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive).
    };

또한, 조건이 겹치는 패턴을 사용해도 오류가 발생합니다. 일례로 아래는 조건식 자체는 다르지만 결국 같은 조건에 해당하므로 컴파일 오류가 발생합니다.

static int CheckSwitch(IList values)
{
    switch (values)
    {
        // error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.
        case [_, .., 1]: return 1;
        case [.., _, 1]: return 2;
    }

    return 0;
}

반면, 아래는 2개의 조건이 확실하게 다르므로 잘 동작합니다.

IList<int> list1 = new List<int>(new[] { 1, 1, 2, 3 });
Console.WriteLine(CheckSwitch(list1)); // 1

IList<int> list2 = new List<int>(new[] { 5, 6, 1, 9 });
Console.WriteLine(CheckSwitch(list2)); // 2

static int CheckSwitch(IList values)
{
    const int condition = 1;

    switch (values)
    {
        case [_, 1, ..]: return 1;
        case [.., condition, _]: return 2;
    }

    return 0;
}

나아가 기존의 패턴 문법과 병용한다면 좀 더 풍부한 조건을 만들 수 있습니다.

ArrayList arr1 = new ArrayList(new[] { 1, 3, 5 });
Console.WriteLine(CheckSwitch(arr1)); // 1

ArrayList arr2 = new ArrayList(new[] { 1, 10, 5 });
Console.WriteLine(CheckSwitch(arr2)); // 1

static int CheckSwitch(ArrayList values)
    => values switch
        {
            [_, >= 3, ..] or [_, <= 10, ..] => 1,
            [..] => -1,
        };

List<int[]> list = new List<int[]>(new[] { new[] { 1, 10, 5 } });
Console.WriteLine(CheckSwitch(list)); // 1

static int CheckSwitch(List<int[]> values)
    => values switch
    {
        [ [1, .., 5] ] => 1,
        [..] => -1,
    };

목록 패턴을 위한 대상은 다음의 요건만 갖추면 어떤 객체든 올 수 있습니다.

  1. Count 또는 Length 속성 제공
  2. indexer 속성 제공

대개의 경우, 위와 같은 조건은 IList 인터페이스를 구현하면 만족하는데요, 어쨌든 최대한 간단하게 위의 목록을 만족하는 클래스는 이런 식으로 정의할 수 있습니다.

NaturalNumber list = new NaturalNumber();
if (list is [1, .., Int32.MaxValue])
{
    Console.WriteLine(true); // True
}

public class NaturalNumber
{
    int _length = Int32.MaxValue;

    public int this[int index]
    {
        get { return index + 1; }
    }

    public int Length => _length;

    // 또는,
    // public int Count => _length;
}

마지막으로, 패턴 내의 슬라이스 기호(..)로 대표되는 결과를 변수로 받아오는 것도 가능합니다.

// 예제 코드: https://devblogs.microsoft.com/dotnet/early-peek-at-csharp-11-features/

public static string CaptureSlice(int[] values)
    => values switch
    {
        [1, .. var middle, _] => $"Middle {String.Join(", ", middle)}",
        [.. var all] => $"All {String.Join(", ", all)}"
    };

사용자 타입에서 저렇게 슬라이스 기호를 이용한 변수를 사용하려면 그에 따라 System.Range를 받아들이는 indexer를 함께 구현해야 합니다.

NaturalNumber list = new NaturalNumber();

if (list is [1, .. var middle, Int32.MaxValue])
{
    foreach (var elem in middle.Take(10))
    {
        Console.Write($"{elem},"); // 출력 결과: 2,3,4,5,6,7,8,9,10,11,
    }
}

public class NaturalNumber
{
    int _length = Int32.MaxValue;

    public int this[int index]
    {
        get { return index + 1; }
        set { }
    }

    public IEnumerable<int> this[System.Range range]
    {
        get
        {
            int startPos = range.Start.Value + 1;
            int endPos = _length - range.End.Value - startPos + 1;

            if (range.End.IsFromEnd == false)
            {
                endPos = range.End.Value - startPos + 1;
            }

            return Enumerable.Range(startPos, endPos);
        }
    }

    public int Length => _length;

    // 또는,
    // public int Count => Int32.MaxValue;
}

한 가지 제약이라면, 슬라이스로 지정한 영역을 변수로 받아오는 것은 (and는 가능하지만) not, or 패턴이 함께 지정된 목록 패턴에서는 사용할 수 없습니다.

// A variable may not be declared within a 'not' or 'or' pattern.
[_, >= 3, ..] or [_, <= 10, .. var rest] => 1,

따지고 보면 당연한 결과입니다. or 패턴의 경우 "Short-circuit Evaluation"이 발생하는 데다 변수로 받게 되는 결과가 해당 조건이 참이어서 받는 경우라면 상관없겠지만 다른 or 조건이 참이어서 받는 경우라면 가능하지 않는 상황일 수 있기 때문입니다. not 패턴 역시 그 조건이 아닌 목록에 대해 슬라이스 영역을 받게 되는 것이므로 undefined와 같은 상태가 될 수 있습니다.

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




C# 11 - 인터페이스 내에 정적 추상 메서드 정의 가능 (공식 문서, Static Abstract Members In Interfaces C# 10 Preview)
; https://www.sysnet.pe.kr/2/0/12814

C# 11 - 제네릭 타입의 특성 적용 (공식 문서, Generic attributes)
; https://www.sysnet.pe.kr/2/0/12839

C# 11 - 사용자 정의 checked 연산자 (공식 문서, Checked user-defined operators)
; https://www.sysnet.pe.kr/2/0/13099

C# 11 - shift 연산자 재정의에 대한 제약 완화 (공식 문서, Relaxing Shift Operator)
; https://www.sysnet.pe.kr/2/0/13100

C# 11 - IntPtr/UIntPtr과 nint/unint의 통합 (공식 문서, Numeric IntPtr)
; https://www.sysnet.pe.kr/2/0/13111

C# 11 - 새로운 연산자 ">>>" (Unsigned Right Shift) (공식 문서, Unsigned right shift operator)
; https://www.sysnet.pe.kr/2/0/13110

C# 11 - 원시 문자열 리터럴 (공식 문서, raw string literals)
; https://www.sysnet.pe.kr/2/0/13085

C# 11 - 문자열 보간 개선 2가지 (공식 문서, Allow new-lines in all interpolations)
; https://www.sysnet.pe.kr/2/0/13086

C# 11 - 목록 패턴 (공식 문서, List patterns)
; https://www.sysnet.pe.kr/2/0/13112

C# 11 - Span 타입에 대한 패턴 매칭 (공식 문서, Pattern matching on ReadOnlySpan<char>)
; https://www.sysnet.pe.kr/2/0/13113

C# 11 - Utf8 문자열 리터럴 지원 (공식 문서, Utf8 Strings Literals)
; https://www.sysnet.pe.kr/2/0/13096

C# 11 - ref struct에 ref 필드를 허용 (공식 문서, ref fields)
; https://www.sysnet.pe.kr/2/0/13015

C# 11 - 파일 범위 내에서 유효한 타입 정의 (공식 문서, File-local types)
; https://www.sysnet.pe.kr/2/0/13117

C# 11 - 메서드 매개 변수에 대한 nameof 지원 (공식 문서, nameof(parameter))
; https://www.sysnet.pe.kr/2/0/13122

C# 11 - 멤버(속성/필드)에 지정할 수 있는 required 예약어 추가 (공식 문서, Required members)
; https://www.sysnet.pe.kr/2/0/13123

C# 11 - 구조체 필드의 자동 초기화 (공식 문서, auto-default structs)
; https://www.sysnet.pe.kr/2/0/13125

C# 11 - 정적 메서드에 대한 delegate 처리 시 cache 적용 (공식 문서, Cache delegates for static method group)
; https://www.sysnet.pe.kr/2/0/13126

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





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







[최초 등록일: ]
[최종 수정일: 5/5/2023]

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

비밀번호

댓글 작성자
 



2022-09-23 11시17분
정성태

... 46  47  48  49  50  51  52  53  54  55  [56]  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12247정성태6/29/202010087.NET Framework: 918. C# - 불린 형 상수를 반환값으로 포함하는 3항 연산자 사용 시 단축 표현 권장(IDE0075) [2]파일 다운로드1
12246정성태6/29/202010878.NET Framework: 917. C# - USB 관련 ETW(Event Tracing for Windows)를 이용한 키보드 입력을 감지하는 방법
12245정성태6/24/202011393.NET Framework: 916. C# - Task.Yield 사용법 (2) [2]파일 다운로드1
12244정성태6/24/202011210.NET Framework: 915. ETW(Event Tracing for Windows)를 이용한 닷넷 프로그램의 내부 이벤트 활용 [1]파일 다운로드1
12243정성태6/23/20208749VS.NET IDE: 147. Visual C++ 프로젝트 - .NET Core EXE를 "Debugger Type"으로 지원하는 기능 추가
12242정성태6/23/20209560오류 유형: 623. AADSTS90072 - User account '...' from identity provider 'live.com' does not exist in tenant 'Microsoft Services'
12241정성태6/23/202012832.NET Framework: 914. C# - Task.Yield 사용법파일 다운로드1
12240정성태6/23/202014103오류 유형: 622. 소켓 바인딩 시 "System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions" 오류 발생
12239정성태6/21/202010708Linux: 30. (윈도우라면 DLL에 속하는) .so 파일이 텍스트로 구성된 사례 [1]
12238정성태6/21/202010524.NET Framework: 913. C# - SharpDX + DXGI를 이용한 윈도우 화면 캡처 라이브러리
12237정성태6/20/202010302.NET Framework: 912. 리눅스 환경의 .NET Core에서 "test".IndexOf("\0")가 0을 반환
12236정성태6/19/202010638오류 유형: 621. .NET Standard 대상으로 빌드 시 dynamic 예약어에서 컴파일 오류 - error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'
12235정성태6/19/202010314오류 유형: 620. Windows 10 - Inaccessible boot device 블루 스크린
12234정성태6/19/20209932개발 환경 구성: 494. NuGet - nuspec의 패키지 스키마 버전(네임스페이스) 업데이트 방법
12233정성태6/19/20209704오류 유형: 619. SQL 서버 - The transaction log for database '...' is full due to 'LOG_BACKUP'. - 두 번째 이야기
12232정성태6/19/20208576오류 유형: 618. SharePoint - StoreBusyRetryLater 오류
12231정성태6/15/202011131.NET Framework: 911. Console/Service Application을 위한 SynchronizationContext - AsyncContext
12230정성태6/15/202010431오류 유형: 617. IMetaDataImport::GetMethodProps가 반환하는 IL 코드 주소(RVA) 문제
12229정성태6/13/202012304.NET Framework: 910. USB/IP PROJECT를 이용해 C#으로 USB Keyboard + Mouse 가상 장치 만들기 [1]
12228정성태6/12/202012398.NET Framework: 909. C# - Source Generator를 적용한 XmlCodeGenerator파일 다운로드1
12227정성태6/12/202016375오류 유형: 616. Visual Studio의 느린 업데이트 속도에 대한 원인 분석 [5]
12226정성태6/11/202013641개발 환경 구성: 493. OpenVPN의 네트워크 구성 [4]파일 다운로드1
12225정성태6/11/202012637개발 환경 구성: 492. 윈도우에 OpenVPN 설치 - 클라이언트 측 구성
12224정성태6/11/202020594개발 환경 구성: 491. 윈도우에 OpenVPN 설치 - 서버 측 구성 [1]
12223정성태6/9/202014526.NET Framework: 908. C# - Source Generator 소개 [10]파일 다운로드2
12222정성태6/3/202010359VS.NET IDE: 146. error information: "CryptQueryObject" (-2147024893/0x80070003)
... 46  47  48  49  50  51  52  53  54  55  [56]  57  58  59  60  ...